我想将几个子查询(每个子查询返回一个具有不同行数的列)的输出接收到一个响应中。
我正在尝试以下操作,但它无法正常工作,错误为 [21000] ERROR: more than one row returned by a subquery used as an expression
。
SELECT
(SELECT DISTINCT org_name
FROM table_1
WHERE column1= 1) AS terminal_1,
(SELECT org_name
FROM table_5
WHERE column5= 1) AS cfs_1,
(SELECT DISTINCT org_name
FROM table_4 where column7= 136 ) AS terminals_2,
(SELECT org_name
FROM table_6
WHERE column1=7) AS cfs_2;
我想这样做,以便将来我可以添加更多的子查询,每个子查询也将返回具有不同行数的单个列。是否有实现相同目标的良好做法?谢谢。
编辑 1:输出响应可以是任何逻辑形式。即表格或 JSON。
最佳答案
让我们拥有 PostgreSQL 的优秀 arrays 怎么样? ?
with terminal_1 as (
SELECT array_agg (DISTINCT org_name) as term1_name
FROM table_1
WHERE column1= 1
),
cfs_1 as (
SELECT array_agg (org_name) as cfs1_name
FROM table_5
WHERE column5= 1
),
terminals_2 as (
SELECT array_agg (DISTINCT org_name) as term2_name
FROM table_4 where column7= 136
),
cfs_2 as (
SELECT array_agg (org_name) as cfs2_name
FROM table_6
WHERE column1=7
)
select
term1_name, cfs1_name, term2_name, cfs2_name
from
terminal_1
cross join cfs_1
cross join terminals_2
cross join cfs_2
虽然这并不能达到您想要的效果,但我相信它确实可以按照您的预期方式提供内容。
关于sql - 将具有不同行的多个子查询输出检索到 postgresql 中的单个响应中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47262932/