日期:2014-05-18  浏览次数:20648 次

求助一个查询语句
有三个表:C(课程号,课程名,任课教师,办公室)
S(学号,姓名,年龄,性别)
SC(学号,课程号,分数)
查出至少学习王刚老师所授全部课程的学生姓名。这个SQL语句怎么写?

------解决方案--------------------
select s.姓名 from s,sc 
where s.学号=sc.学号 and sc.课程号 in(
select 课程号 from c where c.任课教师='王刚')
------解决方案--------------------
create table c(class_id int ,class_name varchar(50),teacher varchar(50),room varchar(50))
create table s(student_id int,student_name varchar(50),age int,sex char(2))
create table sc(student_id int,class_id int,score int)

insert into c
select 1,'math','张三','001' union all
select 2,'math','王刚','002'

insert into s
select 1,'王五',14,'男' union all
select 2,'张六',13,'女' union all
select 3,'赵力',14,'男' union all
select 4,'钱一',15,'男'

insert into sc
select '1','2',40 union all
select '2','1',23 union all
select '2','2',34 union all
select '3','1',93 union all
select '4','1',100 

select student_name
from s
where exists
 (
select * from c , sc
where student_id=s.student_id 
and sc.class_id=c.class_id
and c.teacher='王刚'
 )
drop table c,sc,s
------解决方案--------------------
用课程数作比较,感觉不是很好,一时想不出更好的方法

select 姓名
from s,
(
select 学号,count(*) from 
(
select distinct 学号,课程号 
from sc where 课程号 in (select 课程号 from c where 任课教师='王刚')--此子查询查出学过王刚课程的学生
) a 
group by 学号 having count(*)=(select count(*) from C where 任课教师='王刚')
) b --b表查出所学课程数与王刚所教课程数相同的学生学号
where s.学号=b.学号 --最后再与s表连接查出姓名

------解决方案--------------------
SQL code
declare @Count int
select @Count=count(distinct 课程号) from C where 任课教师='王刚'

select aa.姓名
from S aa
inner join SC bb on aa.学号=bb.学号
inner join C cc on bb.课程号=cc.课程号
where cc.任课教师='王刚'
group by aa.姓名
having(count(1))=@Count