
1. Any
1.1. 任意一个
1.2. 选修了任意一门课程的学生
1.2.1. 找出选修了至少一门课程的学生
1.3. 比任何火车都快的飞机
1.3.1. 找出比所有火车都快的飞机
2. All
2.1. 全部
2.2. 吃所有蔬菜的人
2.2.1. 没有任何一种蔬菜他们不吃
3. 问题12
3.1. 选修了全部课程的学生
3.2. sql
- select *
- from student
- where sno not in
- ( select s.sno
- from student s, courses c
- where (s.sno,c.cno) not in (select sno,cno from take) )
复制代码 3.3. 针对每一个学生,找出他们没有选过的课程,最后如果有谁不在其中,则他必定选修了全部课程
3.3.1. 最内层的子查询会返回所有有效的SNO/CNO组合
3.3.2. 中间一层的子查询使用STUDENT表和COURSES表之间的笛卡儿积,返回(假设每一个学生都选修了全部课程)所有可能的SNO/CNO组合,进而过滤掉有效的SNO/CNO组合(只留下了实际上不存在的SNO/CNO组合)
3.3.3. 最外层的查询,只有当SNO不存在于中间一层子查询结果时,才会被保留下来
3.4. DB2
3.5. SQL Server
3.6. 窗口函数COUNT OVER,并使用外连接而不是子查询
3.6.1. sql
- select sno,sname,age
- from (
- select s.sno,s.sname,s.age,
- count(t.cno)
- over (partition by s.sno) as cnt,
- count(distinct c.title) over() as total,
- row_number() over
- (partition by s.sno order by c.cno) as rn
- from courses c
- left join take t on (c.cno = t.cno)
- left join student s on (t.sno = s.sno)
- ) x
- where cnt = total
- and rn = 1
复制代码 3.7. Oracle
3.7.1. sql
- select sno,sname,age
- from (
- select s.sno,s.sname,s.age,
- count(t.cno)
- over (partition by s.sno) as cnt,
- count(distinct c.title) over() as total,
- row_number() over
- (partition by s.sno order by c.cno) as rn
- from courses c, take t, student s
- where c.cno = t.cno (+)
- and t.sno = s.sno (+)
- )
- where cnt = total
- and rn = 1
复制代码 3.8. 外连接到COURSES表,而不是子查询
3.9. PostgreSQL
3.10. MySQL
3.11. 聚合函数COUNT找出选修所有课程的学生
3.11.1. sql
- select s.sno,s.sname,s.age
- from student s, take t
- where s.sno = t.sno
- group by s.sno,s.sname,s.age
- having count(t.cno) = (select count(*) from courses)
复制代码 3.11.2. 使用子查询返回课程总数
3.11.3. 外层查询负责筛选出选修课程数量等于子查询返回值的学生
4. 问题13
4.1. 比任何其他学生年龄都大的学生
4.2. sql
- select *
- from student
- where age not in (select a.age
- from student a, student b
- where a.age < b.age)
复制代码 4.3. 子查询使用笛卡儿积找出A表中年龄小于B表的学生的年龄值
4.4. 唯一不会比其他年龄值小的就是最大年龄值
4.5. 外层查询使用NOT IN,从STUDENT表中筛选出所有AGE不存在于上述子查询返回结果集的行
4.6. DB2
4.7. Oracle
4.8. SQL Server
4.9. 窗口函数MAX OVER找出年龄最大的学生
4.9.1. sql
- select sno,sname,age
- from (
- select s.*,
- max(s.age)over() as oldest
- from student s
- ) x
- where age = oldest
复制代码 4.10. PostgreSQL
4.11. MySQL
4.12. 聚合函数MAX找出年龄最大的学生
4.12.1. sql
- select *
- from student
- where age = (select max(age) from student)
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |