简体   繁体   English

SQL 如何从单个列中的所有值创建 JSON 数组

[英]SQL how to create a JSON array from all the values in a single column

this query below returns a single column from which I want to create a JSON array from:下面的这个查询返回一个列,我想从中创建一个 JSON 数组:

SELECT CP.PageID 
FROM CommClient.dbo.ClientPage AS CP
INNER JOIN CommApp.dbo.Page as P ON CP.PageID = P.PageID 
INNER JOIN CommApp.dbo.PageGroup as PG ON P.PageGroupID = PG.PageGroupID
LEFT JOIN (
   SELECT DISTINCT ParentPageID FROM [CommApp].[dbo].[Page]
) AS PP 
ON P.PageID = PP.ParentPageID
WHERE ClientID = 102 AND P.ApplicationID = 4
ORDER BY P.pageID

在此处输入图片说明

The result I need is and array of values like this: [4000, 4010, 4110 ...]我需要的结果是这样的值数组:[4000, 4010, 4110 ...]

I've tried to add FOR JSON PATH at the end of that query but I'm getting an array of object ([{"pageID":4000},{"pageID":4010},{"pageID":4110} ....) instead of an array of values and I'm at a loss, I'm a newb in SQL... Thanks!我试图在该查询的末尾添加 FOR JSON PATH 但我得到了一个对象数组 ([{"pageID":4000},{"pageID":4010},{"pageID":4110} 。 ...) 而不是一组值,我不知所措,我是 SQL 的新手...谢谢!

There is a function named GROUP_CONCAT in mySQL you can write as follows. mySQL 中有一个名为 GROUP_CONCAT 的函数,你可以写成如下。 Note the group by clause in the end and group_concat in select注意最后的 group by 子句和 select 中的 group_concat

SELECT GROUP_CONCAT(CP.PageID) as PageID
FROM CommClient.dbo.ClientPage AS CP
INNER JOIN CommApp.dbo.Page as P ON CP.PageID = P.PageID 
INNER JOIN CommApp.dbo.PageGroup as PG ON P.PageGroupID = PG.PageGroupID
LEFT JOIN (
   SELECT DISTINCT ParentPageID FROM [CommApp].[dbo].[Page]
) AS PP 
ON P.PageID = PP.ParentPageID
WHERE ClientID = 102 AND P.ApplicationID = 4
GROUP BY CP.PageID
ORDER BY P.pageID

It varies in different DBMS.它在不同的 DBMS 中有所不同。
SQL Server: SQL 服务器:

select '[' + string_agg(<expression>, ',') + ']'
-- the rest of your query

Postgres: Postgres:

select json_agg(<expression>)
-- the rest of your query

Oracle:甲骨文:

select json_arrayagg(<expression>)
-- the rest of your query

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM