数据库子查询

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值