【问题标题】:Get records with nested items node-mysql获取包含嵌套项的记录 node-mysql
【发布时间】:2018-06-07 07:00:23
【问题描述】:

我在我的 expressjs 应用程序中使用 node-mysql 进行数据库查询操作,并且我想从查询中获取嵌套结果。但似乎我找不到一种简单的方法。

在他们的文档中我找到了 Joins with overlapping column names 它可以查询表名并与列嵌套。然而这 不适用于一对多或多对多结构。

以下是表格结构和预期结果的示例。

表格

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 中是否有任何选项可以做同样的事情?

【问题讨论】:

  • 你在这里找什么? MySQL,至少最近的版本,对 JSON 函数有一些支持。但是,我认为您应该在 Node.js 代码中处理这个问题,而不是在 MySQL 中。
  • 嗨,这就是我要问的问题,我想知道 node-mysql 是否支持表关系的嵌套查询结果。类似于 django-restframework 的做法。
  • 通常你会在应用程序端使用某种 ORM 框架来处理这个问题。无论如何,您可能不应该手动构建所需的 JSON 字符串。
  • 是的,可惜现在切换到 ORM 框架为时已晚。因为我的同事在处理来自 db 的数据时,如果没有原始 sql,会感到不舒服。

标签: mysql express node-mysql


【解决方案1】:

您可以使用 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];

【讨论】:

    猜你喜欢
    • 2022-07-21
    • 1970-01-01
    • 2021-12-14
    • 2016-11-10
    • 1970-01-01
    • 2014-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多