请纠正SQL查询代码的问题
本帖最后由 gridrender 于 2012-12-17 13:21:48 编辑
select sno from sc x where x.cno in (select cno from sc where sno='103' )
group by x.sno having count(x.cno)=(select count(cno) from sc where sno='103')
说明:SC是一个学生选课数据表,sno是学生学号,cno是课程编号,上述SQL语句的目标功能是“查询与103号学生选修的课程完全相同的其他学生的学号,即选修课程名称和选修的课程总数均相同”
问题:
(1)103号学生选修的课程是“数据库原理”和“高等数学”两门课程,但是上述代码可以检索到选修了“数据库原理”、“高等数学”和“离散数学”三门课程的106号学生。
(2)为啥上述代码执行之后,多了包含103号学生选修的全部课程,但选修的门数比103号学生多的学生106号。导致上述问题的原因是什么?如何修改?
select x.sno,sname from sc x,s
where s.sno=x.sno
group by x.sno,s.sname having count(x.cno)=(select count(cno) from sc where sno='103')
intersect
select x.sno,s.sname from sc x,s
where s.sno=x.sno and x.cno in (select cno from sc where sno='103' )
group by x.sno,s.sname having count(x.cno)=(select count(cno) from sc where sno='103')
执行上述SQL代码才是我想要的查询结果,为啥呢?
------解决方案--------------------因为前一句没有排除103,如果这样就对了:
select sno from sc x where sno<>103 and x.cno in (select cno from sc where sno='103' )
group by x.sno having count(x.cno)=(select count(cno) from sc where sno='103')
------解决方案--------------------...
抱歉,看错,得这样:
create table sc(sno int,cno int)
insert into sc select 101,1
insert into sc select 101,3
insert into sc select 101,5
insert into sc select 102,2
insert into sc select 102,3
insert into sc select 102,5
insert into sc select 102,6
insert into sc select 103,1
insert into sc select 103,3
insert into sc select 103,5
insert into sc select 104,1
insert into sc select 104,3
insert into sc select 106,1
insert into sc select 106,3
go
select sno from sc x
where sno<>104 and not exists(select 1 from sc where sno=x.sno and cno not in (select cno from sc where sno='104' ))
group by x.sno having count(x.cno)=(select count(cno) from sc where sno='104')
/*
sno
-----------
106
(1 行受影响)
*/
go
drop table sc