本文共 2338 字,大约阅读时间需要 7 分钟。
在SQL中,一个select from where
语句作为一个查询块。将一个查询块嵌套在另一个查询块的where
子句或having
子句中成为嵌套查询。
以下代码示例展示了嵌套查询的概念:
select Sname from Studentwhere Sno in ( select Sno from SC where Cno = '2');
select
语句不能使用order by
子句。order by
子句只能对最终查询结果进行排序。-- 解法一select Sno, Sname, Sdept from Studentwhere Sdept = 'CS';-- 解法二(自身链接)select S1.Sno, S1.Sname, S1.Sdept from Student S1, Student S2where S1.Sdept = S2.Sdept and S2.Sname = '刘晨';
Student
表来筛选条件。where
条件依赖于父查询中的某个字段。select Sno, Cno from SCwhere Grade > ( select avg(Grade) from SC where Sno = x.Sno);
x
是SC
表的别名,表示一个元组变量。Sno
。any
:子查询结果中的某个值满足条件。all
:子查询结果中的所有值满足条件。select Sname, Sage from Studentwhere Sage < any( select sage from Student where Sdept = 'CS') and Sdept != 'CS';
any
表示子查询结果中的某个值满足条件。select Sname, Sage from Studentwhere Sage < all( select sage from Student where Sdept = 'CS') and Sdept != 'CS';
all
表示子查询结果中的所有值都满足条件。EXISTS
或NOT EXISTS
谓词的子查询不会返回任何数据。select Sname from Studentwhere exists( select * from SC where Sno = Student.Sno and Cno = '2');
exists
子查询用于判断是否存在满足条件的记录。select Sname from Studentwhere not exists( select * from SC where Sno = Student.Sno and Cno = '1');
not exists
用于判断是否存在满足条件的记录。select Sname from Studentwhere not exists( select * from Course where not exists( select * from SC where Sno = Student.Sno and Cno = Course.Cno ));
not exists
用于判断是否存在满足条件的记录。select distinct Sno from SCwhere not exists( select * from SC where Sno = '201215122' and not exists( select * from SC where Sno = SCX.Sno and SC.Cno = SCY.Cno ));
not exists
用于判断是否存在满足条件的记录。转载地址:http://irck.baihongyu.com/