union联合合并:将多条查询语句的结果合并成一个结果
语法:
SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2
......
注:默认地,UNION 操作符选取不同的值。如果允许重复的值,请使用 UNION ALL
SQL UNION ALL 语法
SELECT column_name(s) FROM table_name1
UNION ALL
SELECT column_name(s) FROM table_name2
......
应用场景:.
要查询的结果来自于多个表,且多个表没有直接的连接关系,但查询的信息一致时
特点:
1、要求多条查询语句的查询列数是一致的!
2、要求多条查询语句的查询的每一列的类型和顺序建议一致
3、union关键字默认去重,如果使用union all 可以包含重复项
student表
name |
sex |
age |
subject |
score |
teacher_id |
张三 |
男 |
15 |
语文 |
80 |
1 |
李四 |
女 |
15 |
语文 |
85 |
1 |
王二 |
男 |
16 |
语文 |
65 |
2 |
张三 |
男 |
15 |
英语 |
86 |
3 |
李四 |
女 |
15 |
英语 |
77 |
3 |
王二 |
男 |
16 |
英语 |
56 |
4 |
张三 |
男 |
15 |
98 |
5 |
|
李四 |
女 |
15 |
数学 |
76 |
6 |
王二 |
男 |
16 |
数学 |
54 |
6 |
teacher表
id |
name |
sex |
age |
1 |
张行 |
男 |
45 |
2 |
柳青青 |
女 |
35 |
3 |
杨逍遥 |
男 |
27 |
4 |
胡月华 |
女 |
55 |
5 |
李丽 |
女 |
38 |
6 |
王志杰 |
男 |
41 |
引入案例:查询语文成绩大于60 或 数学成绩大于80的学生信息
select * from student
where (subject ='语文' and score >60) or (subject ='数学' and score >80)
使用union实现
select * from student
where (subject ='语文' and score >60)
union
select * from student
where (subject ='数学' and score >80)
查询男性学生及男性老师的信息
select name,sex from student where sex ='男'
union
select name,sex from teacher where sex ='男'