gpt4 book ai didi

json - 使用 FOR JSON PATH 创建嵌套 JSON 数组

转载 作者:行者123 更新时间:2023-12-02 08:31:55 25 4
gpt4 key购买 nike

我需要从一个查询创建一个 JSON 输出,该查询在两个具有一对多关系的表之间使用内部联接。
我希望辅助表的值嵌套为主表的数组属性。

考虑以下示例:

DECLARE @Persons AS TABLE
(
person_id int primary key,
person_name varchar(20)
)

DECLARE @Pets AS TABLE
(
pet_owner int, -- in real tables, this would be a foreign key
pet_id int primary key,
pet_name varchar(10)
)

INSERT INTO @Persons (person_id, person_name) VALUES
(2, 'Jack'),
(3, 'Jill')

INSERT INTO @Pets (pet_owner, pet_id, pet_name) VALUES
(2, 4, 'Bug'),
(2, 5, 'Feature'),
(3, 6, 'Fiend')

并查询:

DECLARE @Result as varchar(max)
SET @Result =
(
SELECT person_id as [person.id],
person_name as [person.name],
pet_id as [person.pet.id],
pet_name as [person.pet.name]
FROM @Persons
JOIN @Pets ON person_id = pet_owner
FOR JSON PATH, ROOT('pet owners')
)

PRINT @Result

这将打印以下 JSON:

{
"pet owners":
[
{"person":{"id":2,"name":"Jack","pet":{"id":4,"name":"Bug"}}},
{"person":{"id":2,"name":"Jack","pet":{"id":5,"name":"Feature"}}},
{"person":{"id":3,"name":"Jill","pet":{"id":6,"name":"Fiend"}}}
]
}

但是,我希望将宠物数据作为所有者数据中的数组:

{
"pet owners":
[
{
"person":
{
"id":2,"name":"Jack","pet":
[
{"id":4,"name":"Bug"},
{"id":5,"name":"Feature"}
]
}
},
{
"person":
{
"id":3,"name":"Jill","pet":
{"id":6,"name":"Fiend"}
}
}
]
}

我该怎么做?

最佳答案

您可以使用以下查询:

SELECT pr.person_id AS [person.id], pr.person_name AS [person.name],
(
SELECT pt.pet_id AS id, pt.pet_name AS name
FROM @Pets pt WHERE pt.pet_owner=pr.person_id
FOR JSON PATH
) AS [person.pet]
FROM @Persons pr
FOR JSON PATH, ROOT('pet owners')

有关详细信息,请参阅 https://blogs.msdn.microsoft.com/sqlserverstorageengine/2015/10/09/returning-child-rows-formatted-as-json-in-sql-server-queries/

关于json - 使用 FOR JSON PATH 创建嵌套 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47814217/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com