SQL 在 PostgreSQL 中合并两个 SELECT 查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15849423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 14:40:56  来源:igfitidea点击:

Combine two SELECT queries in PostgreSQL

sqlpostgresqlunioncommon-table-expression

提问by Bwyss

I would like to combine two select queries with UNION.
How can I use the result from the first SELECTin the second SELECT?

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

回答by Erwin Brandstetter

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

使用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

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

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