标签: sql postgresql union common-table-expression
我想将两个选择查询与UNION结合起来 如何使用第二个SELECT中第一个SELECT的结果?
UNION
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> )
答案 0 :(得分:18)
使用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
您最希望UNION ALL而不是UNION。不排除重复,并且这种方式更快。</ p>
UNION ALL