6

我们正在尝试使用 SQL Server 2016 中的 FOR JSON 路径从 SQL 查询中形成嵌套数组。

SQL查询:

SELECT A, 
B.name as [child.name],
B.date as [child.date]
 from Table 1 join Table 2 on Table 1.ID=Table 2.ID FOR JSON PATH

期望的输出:

[{
A:"text",
   "child:"[
         {"name":"value", "date":"value"},
         {"name":"value", "date":"value"}

       ]
}]

然而我们得到的是:

 [{
    A:"text",
    "child:" {"name":"value", "date":"value"}
  },
{
   A:"text",
  "child":{"name":"value", "date":"value"}
}]

我们如何使用 FOR JSON PATH 来形成嵌套的子数组。

4

2 回答 2

5

而不是 join 使用嵌套查询,例如:

SELECT A
     , child=(
           SELECT B.name as [child.name]
                , B.date as [child.date] 
           FROM Table 2
           WHERE Table 2.ID = Table 1.ID 
           FOR JSON PATH
       )
from Table 1 FOR JSON PATH

(问题中的查询被破坏了,所以这个查询同样被破坏,但应该给你这个想法)

于 2017-08-18T00:51:22.033 回答
0

假设这个模式:

create table parent(id int primary key, name varchar(100));
create table child(id int primary key, name varchar(100), parent_id int references parent(id));

这是一个可行的解决方案——虽然更复杂——不涉及相关的子查询,只使用FOR JSON PATH

SELECT
  parent.name AS [name],
  child.json_agg AS [children]
FROM parent
JOIN (
  SELECT
    child.parent_code,
    JSON_QUERY(CONCAT('[', STRING_AGG(child.json, ','), ']')) AS json_agg
  FROM (
    SELECT
      child.parent_code,
      (SELECT
        child.name AS [name]
        FOR JSON PATH, WITHOUT_ARRAY_WRAPPER
      ) AS json
    FROM child
  ) AS child
  GROUP BY child.parent_code
) AS child
ON child.parent_code = parent.code
FOR JSON PATH

如果您在 上有一个索引child.parent_id,那么按照建议使用相关子查询,或者等效的 withCROSS/OUTER APPLY可能更有效:

SELECT
  parent.name AS [name],
  child.json AS [children]
FROM parent
OUTER APPLY (
  SELECT
    name AS [name]
  FROM child
  WHERE child.parent_id = parent.id
  FOR JSON PATH
) child(json)
FOR JSON PATH

两个查询都将返回:

[
    {
        "name": "foo",
        "children": [
            { "name": "bar" },
            { "name": "baz" }
        ]
    }
]
于 2021-09-20T16:19:07.713 回答