UNION 子句
描述
该语句用于对多个 SELECT 查询的结果进行集合操作。
使用限制及注意事项
-
集合运算符具有相同的优先级。如果 SQL 语句包含多个集合运算符,则 seekdb 将按照从左到右的顺序对它们进行计算,除非使用括号明确指定了运算的顺序。
-
各个集合运算符只能操作
SELECT语句的结果集,且各个结果集的列数和数据类型必须相同。
语法
select_stmt
{UNION | UNION ALL | MINUS | EXCEPT | INTERSECT} select_stmt
[, {UNION | UNION ALL | MINUS | EXCEPT | INTERSECT} select_stmt ...]
[ORDER BY order_by_condition_list]
[LIMIT limit_clause];
参数解释
| 参数 | 描述 |
|---|---|
| select_stmt | 用于集合计算的 SELECT 语句。有关 SELECT 语句的介绍信息,参见 SELECT。 |
| UNION | 用于将两个 SELECT 语句的结果集合并为一个集合,并去除重复的行。 |
| UNION ALL | 用于将两个 SELECT 语句的结果集合并为一个集合,不去除重复的行。 |
| MINUS | EXCEPT | 用于返回前一个 SELECT 语句的结果集中不包含在后一个 SELECT 语句的结果集中的行。MINUS 是 EXCEPT 的同义词。 |
| INTERSECT | 用于返回两个 SELECT 语句的结果集的交集,并去重。 |
| ORDER BY order_by_condition_list | 用于指定集合计算后进行排序。 |
| LIMIT limit_clause | 用于指定集合计算后返回的行数。 |
示例
-
创建表
test_tbl1和test_tbl2。CREATE TABLE test_tbl1 (col1 INT, col2 INT);
CREATE TABLE test_tbl2 (col1 INT, col2 INT); -
向表
test_tbl1和test_tbl2中插入测试数据。INSERT INTO test_tbl1 VALUES (1, 1), (2, 2), (4, 4);
INSERT INTO test_tbl2 VALUES (2, 2), (3, 3), (5, 5);
-
从表
test_tbl1和test_tbl2中选择col1和col2列的数据,并使用UNION ALL操作符将它们合并到一个结果集中,将保留重复的行。SELECT col1, col2 FROM test_tbl1
UNION ALL
SELECT col1, col2 FROM test_tbl2;返回结果如下:
+------+------+
| col1 | col2 |
+------+------+
| 1 | 1 |
| 2 | 2 |
| 4 | 4 |
| 2 | 2 |
| 3 | 3 |
| 5 | 5 |
+------+------+
6 rows in set (0.023 sec) -
从表
test_tbl1和test_tbl2中选择col1和col2列的数据,并使用UNION操作符将它们合并到一个结果集中,将去除重复的行。SELECT col1, col2 FROM test_tbl1
UNION
SELECT col1, col2 FROM test_tbl2;返回结果如下:
+------+------+
| col1 | col2 |
+------+------+
| 1 | 1 |
| 2 | 2 |
| 4 | 4 |
| 3 | 3 |
| 5 | 5 |
+------+------+
5 rows in set (0.021 sec) -
从
test_tbl1表和test_tbl2表中选择col1和col2列的数据,并返回两个表的交集。即返回test_tbl1和test_tbl2中col1和col2列的数据中重复的部分。SELECT col1, col2 FROM test_tbl1
INTERSECT
SELECT col1, col2 FROM test_tbl2;返回结果如下:
+------+------+
| col1 | col2 |
+------+------+
| 2 | 2 |
+------+------+
1 row in set (0.013 sec) -
从
test_tbl1表中选择col1和col2列的数据,然后排除test_tbl2表中相同的col1和col2列的数据。即返回test_tbl1中有而test_tb2中没有的数据行。SELECT col1, col2 FROM test_tbl1
EXCEPT
SELECT col1, col2 FROM test_tbl2;返回结果如下:
+------+------+
| col1 | col2 |
+------+------+
| 1 | 1 |
| 4 | 4 |
+------+------+
2 rows in set (0.011 sec) -
从
test_tbl1和test_tbl2中获取col1和col2的数据,并将它们合并在一起。然后对合并后的结果按col1降序进行排序,并且只返回前 3 个结果。SELECT col1, col2 FROM test_tbl1
UNION
SELECT col1, col2 FROM test_tbl2
ORDER BY col1 DESC
LIMIT 3;返回结果如下:
+------+------+
| col1 | col2 |
+------+------+
| 5 | 5 |
| 4 | 4 |
| 3 | 3 |
+------+------+
3 rows in set (0.012 sec)