Combine two SELECT queries in PostgreSQL

和自甴很熟 提交于 2020-01-09 19:49:19

问题


I would like to combine two select queries with UNION.
How can I use the result from the first SELECT in the second 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> )

回答1:


Use a CTE to reuse the result from a subquery in more than one SELECT.
You need PostgreSQL 8.4+ for that:

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

You most probably want UNION ALL instead of UNION. Doesn't exclude duplicates and is faster this way.



来源:https://stackoverflow.com/questions/15849423/combine-two-select-queries-in-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!