1-数据准备
students表
name | age | sex | class |
---|---|---|---|
zhangsan | 16 | man | class-one |
lisi | 17 | man | class-one |
hanmeimei | 18 | female | class-one |
employees表
name | age | sex | department |
---|---|---|---|
lisi | 17 | man | IT |
lilei | 22 | man | data |
这是我准备的2张表,2张表都包含name,age,sex字段
2-union all 操作
UNION all 用于把来自多个 SELECT 语句的结果组合到一个结果集合中
select name,age,sex from students
union all
select name,age,sex from employees
name | age | sex |
---|---|---|
zhangsan | 16 | man |
lisi | 17 | man |
hanmeimei | 18 | female |
lisi | 17 | man |
lilei | 22 | man |
请注意:有2条一样的数据!
3-union操作
union类似于union all
但是会把结果集中重复的记录删掉
select name,age,sex from students
union
select name,age,sex from employees
name | age | sex |
---|---|---|
zhangsan | 16 | man |
lisi | 17 | man |
hanmeimei | 18 | female |
lilei | 22 | man |
4-注意
1、当我们知道表中的数据一定不会存在重复的时候,最好使用union all 以提高效率
2、第一个select查询语句使用的字段名称就是最终结果集使用的字段名称
3、每一个select查询的字段名可以不同【毕竟最终采用的是第一个select语句的查询字段名】,但是类型必须相同