以下是查询:
SELECT [C].[Id],
[C].[Name],
[Module].[Id],
[Module].[Name]
FROM [dbo].[Category] [C]
INNER JOIN [CategoryModule] [CM]
ON [C].[Id] = [CM].[CategoryId]
CROSS APPLY (SELECT [M].[Id], [M].[Name] FROM [Module] [M]
WHERE [M].[Id] = [CM].[ModuleId]) [Module]
WHERE [C].[Id]IN (1,2)
FOR JSON AUTO
输出:
[
{"Id":1,"Name":"Book","Module":[{"Id":1,"Name":"Unit"}]},
{"Id":2,"Name":"Business","Module":[{"Id":1,"Name":"Unit"}]},
{"Id":1,"Name":"Book","Module":[{"Id":2,"Name":"App"}]}
]
需要:
[
{"Id":1,"Name":"Book","Module":[{"Id":1,"Name":"Unit"},{"Id":2,"Name":"App"}]},
{"Id":2,"Name":"Business","Module":[{"Id":1,"Name":"Unit"}]}
]
它为同一主表项生成单独的对象。
答案 0 :(得分:0)
您好我认为可以使用FOR JSON AUTO
,OPENJSON
和JSON_MODIFY
我有同样的问题,但我终于找到了解决方案
在你的情况下试试这个
SELECT
JSON_MODIFY (
(SELECT value FROM OPENJSON((SELECT * FROM Category WHERE Id = C.Id FOR JSON AUTO),'$')),
'$.Module',
(SELECT M.Id, M.Name FROM CategoryModule CM INNER JOIN Module M ON CM.ModuleId= M.Id WHERE CM.CategoryId= C.Id FOR JSON AUTO)
) AS Category
FROM Category C
FOR JSON AUTO
输出
[{
"Category": {
"Id": 1,
"Name": "Book",
"Module": [{
"Id": 1,
"Name": "Unit"
}, {
"Id": 2,
"Name": "App"
}]
}
}, {
"Category": {
"Id": 2,
"Name": "Business",
"Module": [{
"Id": 1,
"Name": "Unit"
}]
}
}]