sql - 将具有不同行的多个子查询输出检索到 postgresql 中的单个响应中

标签 sql postgresql

我想将几个子查询(每个子查询返回一个具有不同行数的列)的输出接收到一个响应中。

我正在尝试以下操作,但它无法正常工作,错误为 [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/

相关文章:

sql - 将数组传递给 Rails where 方法

postgresql - 无法在 CentOS 6.7 上启动 Postgresql-9.5 服务

postgresql - 如何运行一系列 SQL 查询并保存结果?

sql - Timescale run_job() 找不到定义的函数/过程

arrays - 错误 : operator does not exist: jsonb[] -> integer

php - 是否可以对连接的列执行全文搜索?

sql - Informix SQL/在另一个查询中重用存储过程的结果

sql - 在 SQL Server 中存储文件与 Amazon S3 之类的东西

java - 在 sql 中执行计算与在您的应用程序中执行计算的优缺点是什么

python - 我应该在 django/postgresql 中删除或设置一个变量为 "deleted"吗?