1.联合查询
union/union all 可以将多张表联合起来查询
区别:union可以对两个表重复的字段去重,union all不会去重
实例
select * from 表A union
select * from 表B
select * from 表A union all
select * from 表B
2.子查询
定义:子查询是一个嵌套在select、insert、update或delete语句中的查询,数据库引擎将子查询作为虚表执行查询操作。子查询可以作为连接语句中的一个表,也可以作为一个值。子查询的执行依赖于嵌套查询。顺序从内层开始,一层一层向外执行,外层的嵌套查询可以访问内层嵌套查询的结果,相比变量方式执行效率更高,子查询还可以将多表的数据组合在一起。
1.简单子查询
简单子查询的子级查询可以独立运行
select *
from studentinfo
where classId = (select classId from classinfo where className='aaa01')
2.相关子查询
子级查询不能独立运行,要依赖主查询数据。
select
(select name from studentinfo where studentId=e.studentId),
(select courseName from courseinfo where courseId = e.courseId),
score
from examinfo e
3.将子级查询作为一个表查询
select
s.name,e.courseId,e.score
from studentInfo s
join examinfo e
on s.studentId =e.studentId
join (
select
courseId , max(score) max_score
from examInfo
group by courseId
) as c
on e.courseId = c.courseId and e.score = c.max_score