首页 > 解决方案 > 获取列值作为不同属性的数组列表

问题描述

我正在尝试编写一个查询来获得这个结果:

[{
    "server_name": "windows",
    "app_names": ["firebase", "news api", "video api"]
}, {
    "server_name": "linux",
    "app_names": ["game"]
}]

然而,这是我得到的结果:

[{
    "server_name": "windows",
    "app_names": ["firebase", "news api", "video api", "game"]
}, {
    "server_name": "linux",
    "app_names": ["firebase", "news api", "video api", "game"]
}]

数据库表:

A
server_id | server_name
-----------------------
1           windows
2           Linux


B
app_id | app_name
-----------------------
1        firebase
2        news api
3        video api
4        game


C
status_id | status  | server_id | app_id
----------------------------------------
1           UP          1           1
2           DOWN        1           2
3           DOWN        1           3
4           DOWN        2           4

我有的查询:

SET @output = (
    SELECT DISTINCT A.server_name,
        JSON_QUERY(REPLACE(REPLACE(( SELECT
            B.app_name
            FROM B
                INNER JOIN C ON
                    B.app_id = C.app_id
                INNER JOIN A ON
                    C.server_id = A.server_id
            FOR 
                JSON AUTO
            ), N'{"app_name":', N''),'"}', '"'
        )) AS [app_names]
    FROM
        A
    FOR JSON PATH
)

我接近我想要的结果,但不知道我错过了什么。app_names无论我做什么,都会出现。

标签: sqljsonsql-server

解决方案


从子查询中删除,A以便您有一个相关的子查询:

SET @output = (
    SELECT DISTINCT A.server_name,
            JSON_QUERY(REPLACE(REPLACE(( SELECT B.app_name
                                         FROM B JOIN
                                              C
                                              ON B.app_id = C.app_id
                                         WHERE C.server_id = A.server_id
                                         FOR JSON AUTO
                                       ), N'{"app_name":', N''),'"}', '"'
                     )) AS [app_names]
    FROM A
    FOR JSON PATH
   )

推荐阅读