Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PostgreSQL中组合两个SELECT查询_Sql_Postgresql_Union_Common Table Expression - Fatal编程技术网

在PostgreSQL中组合两个SELECT查询

在PostgreSQL中组合两个SELECT查询,sql,postgresql,union,common-table-expression,Sql,Postgresql,Union,Common Table Expression,我想将两个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> ) (从表1中选择carto\u id\u键 其中标记(id=16) 联合 (从表2中选择*) 其

我想将两个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> )
(从表1中选择carto\u id\u键
其中标记(id=16)
联合
(从表2中选择*)
其中carto_id_key=)
使用a在多个
选择中重用子查询的结果

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
。不排除重复项,这样做速度更快。

您真正想要实现的是什么,可以通过简单的联接或子查询实现(如果您只想获得所需的详细信息),而且两个查询的列也不匹配!!我想获得表2中满足第一个选择条件的所有记录如果这是唯一的要求,在阅读文档后,我发现最好的解决方案是:从表1中选择*内部连接表2(表1.carto_id_key=table2.carto_id_key),其中表2.tag_id=16谢谢您的帮助