数据库之子查询三(在SQL语句中使用子查询)

在SQL语句中使用子查询
(select,from,having,where,oder by,create table,create view,insert,update,delete)
一、select子句中子查询:
1.select r.stuID,
   (select stuName
   from tstudent
   where stuID=r.stuID) as stuName,r.result,r.curID
   from tresult r
   where r.stuID='s102203'
   order by r.result asc
   和下面对比:
2.select r.stuID,s.stuName,r.result,r.curID
   from tresult r,tstudent s
   where r.stuID='s102203'
   order by r.result asc
//得到:子查询在这里起到的作用就是在tstudent表中筛选stuName,否则显示的时候所有的stuName将会全出来(如2.)
二、from字句中的子查询:
select r.curID,r.curID,c.curName,r.result
from tcurriculum c,
(select curID,stuID,result
 from tresult) r
where r.curID=c.curID
and r.stuID='s102203'
order by r.result asc
//此时的子查询是从tresult中提取出一个虚拟的子表来用r命名,再执行外查询
三、having子句中的子查询
select r.curID,avg(r.result)
from tresult r,tcurriculum c
where r.curID=c.curID
group by r.stuIDgroup by r.stuID
having r.stuID in       //或者(any,all)
(select stuID
from tstudent
where stuID like 's2%'
)
order by r.stuID
//此时的子查询就是找出having中满足的条件,然后对分组进行限制

 

posted @ 2013-09-09 14:27  SoulReaper  阅读(484)  评论(0编辑  收藏  举报