加入查询返回多行

时间:2015-03-19 12:48:59

标签: postgresql join

我有一个查询

SELECT id_anything FROM table1 JOIN table2 USING (id_tables)

现在,我的情况是:

如果该连接返回table2中的两行,我想显示table1中的id_anything(仅限1行) 如果table2的连接返回1行,我想在table2中显示id_anything。

Ps:来自表2的id_anything返回不同的值

示例数据: 表1

id_tables | id_anything
1         | 1

表2

id_tables | id_anything
1         | 10
1         | 100

预期回报:1

1 个答案:

答案 0 :(得分:0)

首先,获取您可能想要返回的值以及决定将哪些值一起返回到一行的基础。

SELECT table1.id_tables, table1.id_anything AS table1_id, MIN(table2.id_anything) AS table2_id, COUNT(*)
  FROM table1 JOIN table2 USING (id_tables)
  GROUP BY table1.id_tables, table1.id_anything

您使用的聚合函数并不重要,因为如果只有一个函数,您只会使用该值。

然后您可以选择相关值:

WITH join_summary AS (
  SELECT table1.id_tables, table1.id_anything AS table1_id, MIN(table2.id_anything) AS table2_id, COUNT(*) AS match_count   
    FROM table1 JOIN table2 USING (id_tables)
    GROUP BY table1.id_tables, table1.id_anything
)
SELECT id_tables, CASE WHEN (match_count > 1) THEN table1_id ELSE table2_id END AS id_anything
  FROM join_summary