--嵌套查询(2020-3-25)
--in谓词(从内向外)
/*典型的不相关子查询
将内层结果作为外层条件
可以用连接谓词and替代(连接查询)*/
--查询选修了2号课程的学生的姓名
--select Sname
--from student
--where sno in
--(
--select sno
--from sc
--where cno = '2'
--);
--查询与“刘晨”在同一个系的学生 先确定系名,再查询该系的学生
--select * --sno,sname,sdept /*根据系名确定信息*/
--from student
--where sdept in
--(select sdept /*确定 刘晨 所在系的系名*/
-- from student
-- where sname = '刘晨');
--比较查询
--找出每个学生超过他选修课程平均成绩的课程号(典型的相关子查询:父查询给子查询提供条件)
--select sno,cno
--from sc s1
--where s1.grade> /*找出sno,然后将sno传入子查询进行比较查询,如果符合子查询的条件,就传出cno*/
--(select avg(grade)
--from sc s2 /*给sc起别名,因为父查询和子查询都是sc*/
--where s1.sno = s2.sno);
--带有 any 和 all 不相关子查询
--查询其他系中比信息系任意一个(其中某一个)学生年龄小的学生姓名和年龄
--select sname,sage
--from student
--where sage < any /*也可以将any换成some*/
--(
--select sage
--from student
--where sdept = 'IS')
--and sdept <> 'IS';/*这是父查询中的条件,此约束保证所选学生不属于信息系*/
--也可以用max,注意大于小于号 any即存在
--select sname,sage
--from student
--where sage<
--(
--select max(sage)
--from student
--where sdept = 'IS')
--and sdept <> 'IS';
--这个例子属于不相关子查询
--查询其他系中比计算机科学系所有学生年龄小的学生的姓名和年龄
--select sname,sage
--from student
--where sage<all
--(select sage /*选出计算机系所有学生的年龄*/
-- from student
-- where sdept='CS')
-- and sdept<>'CS';/*父查询中的条件,此约束表示所选的学生不属于计算机系*/
/*也可以用min,注意大于小于号 但是如果数据中有NULL的话,结果是不一样的,
上面的查询没有结果(会把null当做最小值,所以没有比它更小的),
下面的正常显示(会忽略掉NULL所在的元组)*/
--select sname,sage
--from student
--where sage<
--(select min(sage) /*选出计算机系所有学生的年龄*/
-- from student
-- where sdept='CS')
--and sdept<>'CS';/*父查询中的条件,此约束表示所选的学生不属于计算机系*/
2020-3-25 嵌套查询
猜你喜欢
转载自blog.csdn.net/u013140841/article/details/105380332
今日推荐
周排行