我在我的expressjs应用程序中使用node-mysql进行数据库查询操作,并且我想从查询中获取嵌套结果。但似乎我找不到一种简单的方法。
In their document I found Joins with overlapping column names which can query a table name and nested with a columns. However this is not suitable work around for one-to-many or many-to-many structure.
以下是表结构和预期结果的示例。
表格
tbl_order
id customer_name date
1 Perona 6/7/2018
2 Zorro 6/8/2018
tbl_order_items
id order_id item_name
1 2 compass
2 2 sword
3 2 yakuta
4 1 umbrella
5 1 doll
预期结果
我想获取所有订单和包含该订单的商品。
[
{
id: 1,
customer_name: perona,
data: 6/7/2018,
items: [
{ id: 4, item_name: umbrella },
{ id: 5, item_name: doll },
]
},
{
id: 2,
customer_name: zorro,
data: 6/8/2018,
items: [
{ id: 1, item_name: compass },
{ id: 2, item_name: sword },
{ id: 3, item_name: yakuta },
]
}
]
是否有任何选项可以在node-mysql
中执行相同的操作?
最佳答案
您可以使用 INNER JOIN 根据关联获取嵌套数据。
SELECT [order].*,
[items].[id] AS [items.id]
[items].[item_name] AS [items.item_name]
FROM
(
SELECT [id],
[customer_name],
[date]
FROM [tbl_order]
) AS [order]
INNER JOIN
[tbl_order_items] AS [items]
ON
[order].[id] = [items].[order_id];
关于mysql - 获取包含嵌套项目的记录node-mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50734815/