包括并集(Union)、交集(Intersect)和差集(Except)。执行SQL集合运算时,集合操作中的两个查询结果需要满足以下条件:
注意
sqlSELECT column1, column2, ...
FROM table1
INTERSECT [DISTINCT | ALL]
SELECT col1, col2, ...
FROM table2;
sql-- oracle mss pg sqlite
SELECT id, name
FROM t_set1
INTERSECT
SELECT id, name
FROM t_set2;
交集运算通常可以改写为内连接。
sqlSELECT DISTINCT t1.id, t1.name
FROM t_set1 t1
JOIN t_set2 t2
ON (t2.id = t1.id AND t2.name = t1.name)
sqlSELECT column1, column2, ...
FROM table1
UNION [DISTINCT | ALL]
SELECT col1, col2, ...
FROM table2;
sqlSELECT id, name
FROM t_set1
UNION
SELECT id, name
FROM table2;
并集运算可以改写为全外连接。
sql-- oracle mss pg
-- COALESCE 返回第一个非空值
SELECT COALESCE(t1.id, t2.id), COALESCE(t1.name, t2.name)
FROM t_set1 t1
FULL JOIN t_set2 t2
ON (t2.id = t1.id AND t2.name = t1.name);
sql-- mysql sqlite
-- mysql 将第一个查询返回的字段转换为字符串类型
-- sqlite 将第二个查询返回的字段转换为整数类型
SELECT 1 AS id
UNION ALL
SELECT 'sql' AS name;
sqlSELECT column1, column2, ...
FROM table1
EXCEPT [DISTINCT | ALL]
SELECT col1, col2, ...
FROM table2;
sql-- oracle 19c以及更早
SELECT id, name
FROM t_set1
MINUS
SELECT id, name
FROM t_set2;
差集运算可以改写为左外连接或右外连接。
sqlSELECT t1.id, t1.name
FROM t_set1 t1
LEFT JOIN t_set2 t2
ON (t2.id = t1.id AND t2.name = t1.name)
WHERE t2.id IS NULL;
想要对集合运算的结果进行排序操作,必须将 ORDER BY 子句写在整个查询语句的最后,集合运算符之前的 SELECT 语句中不能出现排序子句。
sqlSELECT id, name
FROM t_set1
UNION ALL
SELECT id, name
FROM t_set2
ORDER BY id;
sql-- mss pg sqlite
SELECT 1 AS n
UNION ALL
SELECT 1
INTERSECT
SELECT 1;
-- mss pg
/*
n
-
1
1
*/
-- sqlite
/*
n
-
1
*/
--oracle
SELECT 1 AS n FROM dual
UNION ALL
SELECT 1 FROM dual
INTERSECT
SELECT 1 FROM dual;
-- oracle
/*
n
-
1
*/
-- oracle 需要加上 dual 表
SELECT 1 AS N
UNION ALL
SELECT 1
UNION
SELECT 1;
/*
n
-
1
*/
SELECT 1 AS N
UNION
SELECT 1
UNION ALL
SELECT 1;
/*
n
-
1
1
*/
-- 使用括号修改顺序
-- mss pg,oracle 需要加上 dual 表
SELECT 1 AS N
UNION ALL
(SELECT 1
UNION
SELECT 1);
/*
n
-
1
1
*/
本文作者:jdxj
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!