21

我想将两个选择查询与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> )
4

1 回答 1

28

使用CTE在多个SELECT.

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

SELECT carto_id_key
FROM   cte

UNION ALL
SELECT t2.some_other_id_key
FROM   cte
JOIN   table2 t2 ON t2.carto_id_key = ctex.carto_id_key

你很可能想要UNION ALL而不是UNION. 不排除重复项,并且这样更快。

于 2013-04-06T11:32:26.230 回答