mysql数据库里有俩表,已经通过外键连起来了,然后我想html里显示从表里的数据。
在mapper里加了@select 然后嘞?
你可以尝试以下步骤将从表的数据在 HTML 页面中显示出来:
在后端代码中,通过 SQL 查询语句获取主表和从表的数据,并使用 JOIN 操作连接两个表。
将查询结果封装成 JSON 格式的数据,通过 API 接口返回给前端。
在前端页面中,通过 Ajax 请求后端 API 接口,获取数据并将数据展示在 HTML 页面中。可以使用 Vue、React 等前端框架来简化操作。
在 HTML 页面中,使用 v-for 指令(Vue)或者 map() 方法(React)来遍历从表数据,并将数据渲染到页面中。
以下是一个示例代码:
后端代码:
# 获取主表和从表数据的 SQL 查询语句
sql = """
SELECT m.*, s.*
FROM main_table m
LEFT JOIN sub_table s ON m.id = s.main_table_id
"""
# 执行查询,并返回结果
cursor.execute(sql)
results = cursor.fetchall()
# 将结果封装成 JSON 格式的数据,返回给前端
data = []
for row in results:
main_table_data = {
"id": row[0],
"name": row[1],
"description": row[2]
}
sub_table_data = {
"id": row[3],
"main_table_id": row[4],
"sub_table_data": row[5]
}
data.append({
"main_table": main_table_data,
"sub_table": sub_table_data
})
return jsonify(data)
前端代码:
<template>
<div>
<h1>Main Table Data</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr v-for="data in mainTableData" :key="data.id">
<td>{{ data.id }}</td>
<td>{{ data.name }}</td>
<td>{{ data.description }}</td>
</tr>
</tbody>
</table>
<h1>Sub Table Data</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>Main Table ID</th>
<th>Sub Table Data</th>
</tr>
</thead>
<tbody>
<tr v-for="data in subTableData" :key="data.id">
<td>{{ data.id }}</td>
<td>{{ data.main_table_id }}</td>
<td>{{ data.sub_table_data }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
data () {
return {
mainTableData: [],
subTableData: []
}
},
mounted () {
// Ajax 请求后端 API 接口,获取数据
fetch('/api/get_data')
.then(response => response.json())
.then(data => {
this.mainTableData = data.map(item => item.main_table)
this.subTableData = data.map(item => item.sub_table)
})
}
}
</script>
请根据实际情况对代码进行修改。
该回答引用NewBing
你好,这是Bing。😊
根据我搜索到的信息,你可以通过以下几个步骤来实现你的需求:
在mapper里使用@Select注解,写一个多表查询的SQL语句,用主表的外键和从表的主键进行连接,选择你想要显示的从表的字段¹²。
在service层,调用mapper层的方法,返回一个List或者Map类型的数据。
在controller层,接收service层的数据,用ModelAndView或者Model对象将数据传递给前端页面³。
在html页面里,用JSP或者Thymeleaf等模板引擎,遍历数据并显示在表格或者列表中。
希望这些信息对你有帮助。👍
源: 与必应的对话, 2023/3/28
(1) 怎样在html里显示根据主表外键查询到的从表的数据-前端-CSDN问答. https://ask.csdn.net/questions/7910718 访问时间 2023/3/28.
(2) 数据库 —— 浅谈主外键以及多表查询_cccrush_的博客-CSDN博客. https://blog.csdn.net/weixin_42621338/article/details/82710001 访问时间 2023/3/28.
(3) mysql中主表与从表 - Roy-Xin - 博客园. https://www.cnblogs.com/xinruyi/p/11279627.html 访问时间 2023/3/28.