sql - 获取列值作为不同属性的数组列表
问题描述
我正在尝试编写一个查询来获得这个结果:
[{
"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
无论我做什么,都会出现。
解决方案
从子查询中删除,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
)
推荐阅读
- c# - asp.net 中的程序化与声明性数据绑定
- wkwebview - 如何使用 wkwebview 调整网页视图
- html - Bootstrap card-img-overlay 中的锚点标签不可点击
- postgresql - PostgreSQL 中时间戳和分组依据的查询优化
- bash - 带参数的 wget bash 脚本
- python - 将具有多个函数的 python 脚本转换为 SnakeMake 工作流
- python - Pandas read_html() 在特定列上返回“nan”
- typescript - 是否可以使用 TypeDoc 为 TypeScript 项目生成单页文档 html?
- jhipster - Ionic + jHipster + okta 移动应用程序中的 CORS 错误
- rust - 如何处理“未使用的期货::MapErr”警告?