MySQL 学习(四)并集查询
联合查询,它是用 union 关键字把多条 select 语句的查询结果合并为一个结果集。
纵向合并的前提是被合并的结果集的字段数量、顺序和数据类型必须完全一致。字段名不一样的情况下,会将第一个结果集的字段名作为合并后的虚拟结果集的字段名。
select <字段1>[,<字段2>,…] from <表名1>
union[ all]
select <字段1>[,<字段2>,…] from <表名2>;
create table t1(key1 char,v1 int);
create table t2(key2 char,v2 int);
insert into t1 values('a',1),('a',2),('b',3),('c',4),('a',13);
insert into t2 values('b',10),('b',11),('a',12),('a',13),('e',14);
- union 去重
mysql> select * from t1
-> union
-> select * from t2;
+------+------+
| key1 | v1 |
+------+------+
| a | 1 |
| a | 2 |
| b | 3 |
| c | 4 |
| a | 13 |
| b | 10 |
| b | 11 |
| a | 12 |
| e | 14 |
+------+------+
- union all 不去重
mysql> select * from t1
-> union all
-> select * from t2;
+------+------+
| key1 | v1 |
+------+------+
| a | 1 |
| a | 2 |
| b | 3 |
| c | 4 |
| a | 13 |
| b | 10 |
| b | 11 |
| a | 12 |
| a | 13 |
| e | 14 |
+------+------+