sql中的子查询

来源:互联网 发布:淘宝网后台管理 编辑:程序博客网 时间:2024/04/29 01:08
在数据库的查询过程中,可能经常要用到子查询的情况,用得较多的可能是嵌套子查询,以下是我总结的子查询的一些应用
子查询基本分类:独立子查询和相关子查询
独立子查询(子查询可以独立运行)
例:
select
最高分=(select MAX(FMath) from MyStudents),
最低分=(select MIN(FMath) from MyStudents),
平均分=(select AVG(FMath) from MyStudents)
相关子查询(子查询中引用了父查询中的结果)
例:
select * from Student
where
exists(select *
from Class
where cName='高二二班' and Class.clsId=Student.sClassId)
子查询除了可以应用在select中之中,还可以应用在delete、update中。
例:--删除刘备、关羽、张飞的成绩
delete from Score
where studentId in
(Select sId from Student where sName='刘备' or sName='关羽' or sName='张飞')
在where中 可以应用子查询
例:--查询高二二班的所有学生
select * from Student
where sClassId=(
select clsId
from Class where cName='高二二班')
exists子查询
它返回逻辑值true或false,并不生产其他任何实际值。所以这种子查询的选择列表常用“SELECT *”格式。
例:
if(exists(select * from Student))
begin--{
   print '有结果'
end--}
else
begin--{
   print '没结果'
end--}
原创粉丝点击