如题,
我在联系sql时,想做一个查询 学过001课程同时也学过002课程的同学的学号和姓名
的查询时,发现一个问题不理解:
select *
from student s
where (select count(*) from sc where cno = 'c01')>0
这样查询出来的结果是
这是不符合我的想法的,按理来说应该先是内部的select返回的结果应该是3呀,为什么全部输出了?
select *
from student s
where (select count(*) from sc where s.sno= sc.sno and cno = 'c01')>0
这样查询出来的结果却是我想要的结果,
很奇怪为什么需要在where中添加连接表的操作呢?而且这个连接表的操作中为什么from里面不需要from student表,只from sc表就可以操作了?
正常情况下如果连接表应该是
select*
from student,sc
where student.sno = sc.sno
呀 为什么此处不需要from student?
我都不确定这样操作出来什么
求大神帮忙解答解答。
我的student表和sc表如下:
http://bbs.csdn.net/topics/380232971
你可以把你的两张表贴出来,然后再说
一、首先,你前面有了student s的定义,后面内部无需在from student,多此一举;
二、然后后面你那个sc和student是关联的,所以查询你肯定要在内部关联了,不然查询总是大于0,然后肯定输出全部student的情况啊!
select * from students where (select count(* ) from sc where cno = 'c01' )>0
sc表有数据,所有(select count(* ) from sc where cno = 'c01' )>0 恒成立
所以你的sql语句也就相当于select * from students ,当然是查询全部了
第一个应该是只能查询有修读了001课程的学生吧,第二个敢问楼主where s.sno= sc.sno 是什么意思,sc和s分别指的是什么表。
select * from student s where (select count(*) from sc where s.sno= sc.sno and cno = 'c01')>0;
这样做能得到正确结果应该是:在外层的SELECT中重命名了表Student为S,而在内层的SELECT中并没有对Student的表重新命名,也就默认,外层的表S 和内层的表SC连接起来。x简单说就是相当于:select * from student s join sc sc.sno=s.no where cno='co1';而这个结果只会有三行。而内层的select仍然与前面一样,只是会使where 恒成立。