获取列值作为distinct属性的数组列表

eiee3dmh  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(178)

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

[{
    "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 不管我做什么都要出现。

pw9qyyiw

pw9qyyiw1#

拆下 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
   )

相关问题