1

以下是查询:

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"}]}
]

它为相同的主表条目生成单独的对象。

4

1 回答 1

0

嗨,我认为这是可能的使用FOR JSON AUTOOPENJSON并且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"
        }]
    }
}]
于 2018-02-10T23:16:34.070 回答