集合运算符
UNION 和 UNION ALL
UNION 运算符可合并 2 个或多个 SELECT 语句的结果集,并删除各 SELECT 语句之间的重复行。
UNION ALL 运算符可合并 2 个或多个 SELECT 语句的结果集,并返回查询中的所有行,不会删除各 SELECT 语句之间的重复行。
UNION 运算符中的每条 SELECT 语句的结果集必须有相同数量的字段,且数据类型相似。
UNION ALL
运算符的句法如下:
SELECT expression1, expression2, ... expression_n
FROM tables
[WHERE conditions]
UNION ALL
SELECT expression1, expression2, ... expression_n
FROM tables
[WHERE conditions];
expression1, expression2, ... expression_n 是要检索的列或计算。
tables 是要从中检索数据的表。FROM 子句中必须至少列出一个表。
WHERE conditions 是可选项。必须满足这些条件才能选中数据。
假设我们有一个表points_scored_current_week
,包含以下列:id
、first_half
和 second_half
。
id | first_half | second_half |
---|---|---|
1 | 10 | 20 |
接下来,假设我们有第二个表 points_scored_last_week
,包含以下列:id
、first_half
和 second_half
。
id | first_half | second_half |
---|---|---|
1 | 10 | 20 |
下面是一个使用 UNION 运算符的示例:
SELECT *
FROM points_scored_current_week
UNION
SELECT *
FROM points_scored_last_week;
结果如下:
| id |first_half|second_half|
|-------|----------+-----------+
| 1 | 10 | 20 |
下面是一个使用 UNION ALL 运算符的示例:
SELECT *
FROM points_scored_current_week
UNION ALL
SELECT *
FROM points_scored_last_week;
结果如下:
| id |first_half|second_half|
|-------|----------+-----------+
| 1 | 10 | 20 |
| 2 | 10 | 20 |
流式查询支持 UNION 和 UNION ALL 运算符。
INTERSECT
INTERSECT
运算符可合并 2 个或多个 SELECT
语句的结果集,只返回所有 SELECT
语句共有的行,且从最终结果集中删除重复行。
INTERSECT
运算符中的每条 SELECT
语句的结果集必须有相同数量的字段,且数据类型相似。
INTERSECT
运算符的句法如下:
SELECT expression1, expression2, ... expression_n
FROM tables
[WHERE conditions]
INTERSECT
SELECT expression1, expression2, ... expression_n
FROM tables
[WHERE conditions];
expression1, expression2, ... expression_n 是要检索的列或计算。
tables 是要从中检索数据的表。FROM
子句中必须至少列出一个表。
WHERE conditions 是可选项。必须满足这些条件才能选中数据。
假设我们有一个表points_scored_current_week
,包含以下列:id
、first_half
和 second_half
。
id | first_half | second_half |
---|---|---|
1 | 10 | 20 |
接下来,假设我们有第二个表 points_scored_last_week
,包含以下列:id
、first_half
和 second_half
。
id | first_half | second_half |
---|---|---|
1 | 10 | 20 |
下面是一个使用 INTERSECT
运算符的示例:
SELECT *
FROM points_scored_current_week
INTERSECT
SELECT *
FROM points_scored_last_week;
结果如下:
| id |first_half|second_half|
|-------|----------+-----------+
| 1 | 10 | 20 |
在本例中,INTERSECT
运算符返回了 points_scored_current_week
表和 points_scored_last_week
表共有的行。如果没有共有行,INTERSECT
运算符将返回空集。
流式查询支持 INTERSECT
运算符。