目录
建议:可以先看定义,后直接看实例,通过实例自己总结适用情况和使用要求
定义
UNION并查询或复合查询。通常一次查询只有一个结果集,使用Union可以合并多个查询的结果集。
语法:
select 列1,列2 from test1 union select 列1,列2 from test2;
适用情况
- 从多个表中查询相似结构的数据,返回一个结果集
- 从单个表中多次查询,将结果合并返回一个结果集
使用要求
- 查询表的列数必须一致,如果不一致,会报错:两个查询语句列数不同
- 查询表的列的数据结构必须近似(可以发生类型转换)
使用实例
现有两表:test1 和 test2,以下实例都将以这两个表为实例
union VS union all
union 去重,两个表如果查询的列数据一致,那么会将这条数据去除掉
union all 不去重,会查到相同的字段
union
例:采用union 方法,查询两个表的id和name字段,字段内容没有全部重复,所以查到了两表中的全部字段
select id,name from test union select id,name from test2;
例:采用union方法,查询两个表的id字段,字段有重复内容,所以会去掉重复内容
select id from test union select id from test2;
例:采用union方法,查询test表的id和name字段,使用id等于1和等于4000的字段,没有全部重复,所以不会去重
select id,name from test where id = 1 union select id,name from test where id = 4000;
union all
例:采用union all方法,查询两个表的id字段,字段有重复内容,不会去掉重复内容
select id from test union all select id from test2;
区分多表
由于数据来源于多个表,有可能要对于表进行区分,所以可以在使用时候,通过语句新增一个字段来标识不同的表
例:从两个表查询id 并进行标记,第一个表标记为test,第二个表标记为test2
select id,"test" as table_name from test union select id,"test2" as table_name from test2;