子查询
简单来说就是在一个查询里面继续嵌套其他查询语句
根据子查询出现的地方总结:
where子句后面:子查询一般会返回单行单列,单行多列,多行单列的数据
单行单列:select * from ryxx where bianm< (select avg(caozydm) from caozyxx)
单行多列:select * from ryxx where (xingb,zhic) =(select xingb,zhic from ryxx where xingm = '张新琴')
多行单列:select * from ryxx where bianm in (select bianm from ryxx where zhic = '主治医师')
any操作:
select * from ryxx where bianm =any (select bianm from ryxx where zhic = '主治医师')
//功能与in相同
select * from ryxx where bianm >any (select bianm from ryxx where zhic = '主治医师')
//返回的值比子查询返回的最小值要大,意思是查询bianm大于zhic为主治医师返回的bianm中最小的值的所有数据
select * from ryxx where bianm <any (select bianm from ryxx where zhic = '主治医师')
//返回的值比子查询返回的最大值要小,意思是查询bianm小于zhic为主治医师返回的bianm中最大的值的所有数据
all操作:
select * from ryxx where bianm <all (select bianm from ryxx where zhic = '主治医师') order by bianm
//比子查询返回的最小值小的所有数据
select * from ryxx where bianm >all (select bianm from ryxx where zhic = '主治医师') order by bianm
//比子查询返回的最大值大的所有数据
having子句:子查询一般会返回单行单列,同时表示要使用统计函数
select zhic ,count(bianm),trunc(avg(suosks)) from ryxx group by zhic having trunc(avg(suosks)) > (select trunc(avg(suosks)) from ryxx )
from子句:子查询返回多行多列(表结构)相当于一个临时表
Select d.dname,d.loc,temp.count
From dept d,(
Select deptno,count(empno) count from emp group by deptno )temp
Where d.deptno=temp.deptno(+)
另一种使用情况:在整个查询语句中需要使用统计函数,而又无法使用统计函数时,可以先在from子句中利用子查询实现统计
select子句:子查询返回单行单列,一般不使用
``
select r.bianm,r.xingm,(select c.mim from caozyxx c where c.caozydm = r.bianm)from ryxx r
//但同时,这意味着每当有一行数据出现,就会查询一遍caozyxx表,等于用了'1+n'次查询,尽量不使用
性能问题:
使用多表查询实现统计,和子查询实现统计,那个效果好
假设两个表各有500条数据
多表查询:数据量为500乘500条,也就是笛卡尔积
子查询:现在子查询里面实现统计:查询的数据量为500条,返回的统计数据肯定不足500条,然后返回的统计数据作为一个临时表跟另一个表多表连接:也就是500*(500-n)+500条数据 *
ps:只要返回的统计数据不是和原表差不多,子查询的效果都比多表查询实现统计效果要好*
所以在实际情况中,我们常用子查询来解决多表查询带来的性能问题