在PostgreSQL中组合两个SELECT查询

Bwy*_*yss 13 sql postgresql union common-table-expression

我想结合两个选择查询UNION.
如何使用SELECT第二个中的第一个结果SELECT

(SELECT carto_id_key FROM table1
    WHERE tag_id = 16)
UNION 
(SELECT * FROM table2
    WHERE carto_id_key = <the carto_id result from above> )
Run Code Online (Sandbox Code Playgroud)

Erw*_*ter 19

使用CTE重用多个子查询中的结果SELECT.
你需要PostgreSQL 8.4+:

WITH x AS (SELECT carto_id_key FROM table1 WHERE tag_id = 16)

SELECT carto_id_key
FROM   x

UNION ALL
SELECT t2.some_other_id_key
FROM   x
JOIN   table2 t2 ON t2.carto_id_key = x.carto_id_key
Run Code Online (Sandbox Code Playgroud)

你最想要的UNION ALL不是UNION.不排除重复,并且这种方式更快.