嵌套查询 定义: 1.指在一个外层查询中包含有另一个内层查询。其中外层查询称为主查询,内层查询称为子查询。 2.SQL允许多层嵌套,由内而外地进行分析,子查询的结果作为主查询的查询条件 3.子查询中一般不使用order by子句,只能对最终查询结果进行排序 子查询(sub query) where 表达式 [not]in (子查询) where 表达式 比较运算符[any|all] 子查询 where[not]exists (子查询) 1.子查询-单值比较 返回单值子查询,只返回一行一列 主查询与单值子查询之间用比较运算符进行连接: 运算符:>,>=,<,<=,=,<> 例:找出与太行同龄的同事 select*from company where age = (select age from company where name=taihang) 2.子查询-in 例:查询选修了‘001’课程的学生学号,姓名。 select id,name from student where id in (select id from taihang where id='001') 3.子查询-多值比较all 多行一列 1.父查询与多值子查询之间的比较需用all来连接 2.标量值S比子查询返回集R中的每个都大时,s>all,r为true 3.all表示所有 4.>all,<all,>=all,<=all,<>all,注:all等价于not in 例:找出年龄最小的学生 select*from student where age<all(select age from student) 4.子查询-多值比较some/any 1.父查询与多值子查询之间的比较需用some/any来连接 2.标量值S比子查询返回集r中的某一个都大时,s>some时r为true 或s>any时r为true 3.some表示部分 4.>some,>=some,=some,<some,<=some,<>some,注:=some等价于in,<>some不等价于not in. 例:找出不是最小年龄的学生 select*from student where age >some(select age from student) 5.子查询-存在判断exists 1.exists+子查询用来判断该子查询是否返回元组 2.当子查询的结果集非空时,exists为true 3.当子查询的结果集为空时,exists为false 4.不关心子查询的具体内容,因此用select * 例:列出先修了C01课程的学习的学号,姓名 select son,sname from strdent whereexists(select*from sc where sc.sno=stusent.sno and cno='C01') 最后这一个不是很好理解呀!等用多了就好了。