子查询中最后的sc_2=2,为什么不能换成sc=2呢?

查询学过“001”并且也学过编号“002”课程的同学的学号、姓名;

select student.sid,student.sname from student,sc
where student.sid=sc.sid and sc.cid=1 and exists
(select * from sc as sc_2 where sc.sid=sc_2.sid and sc_2.cid=2)

为什么子查询部分的最后必须是sc_2.cid=2,而用sc.cid=2会查到空的呢?
thanks for your anser.

阅读 1.7k
1 个回答

sc.cid已经被限定为1了。sc_2你可以当做一张完全和sc一样的表,但是不是sc。exists子查询select * from table1 where [exist]subquery对表table1进行遍历,查看是否能通过子查询,如果通过则当前行满足条件。
假设sc表保存了选了奇数编号课程(001,003...)的学生选择情况,sc_2表保存了选了偶数编号课程(002,004...)的学生选择情况,

select student.sid,student.sname from student,sc
where student.sid=sc.sid and sc.cid=1 and exists (select * from sc_2 where sc.sid=sc_2.sid and sc_2.cid=2)

这样就比较清楚了。

看下exists子查询的用法中文翻译

推荐问题