这是那三个表
学生表:student 课程表Course 选课表
sno,sname cno,cname sno,cno
0001,张三 001,语文 0001,001
0002,李四 002,数学 0001,002
0003,xxxx 003,英语 0001,003
0002,001
0002,002
,本来想用group by 查询选课表每个人的count(1) 与 课程表count,判断是否相等,但是这两个表没有外键关联,不一定对。请教更好的方法查询
------解决方案--------------------
如果有重复的话,可以先去重,然后再按照去重后的数量来判断!
------解决方案--------------------
没看明白是什么意思
------解决方案--------------------
是不是要这样?
--> 测试数据:[student]
if object_id('[student]') is not null drop table [student]
go
create table [student]([sno] varchar(4),[sname] varchar(4))
insert [student]
select '0001','张三' union all
select '0002','李四' union all
select '0003','xxxx'
--> 测试数据:[ Course]
if object_id('[Course]') is not null drop table [Course]
go
create table [Course]([cno] varchar(3),[cname] varchar(4))
insert [Course]
select '001','语文' union all
select '002','数学' union all
select '003','英语'
--> 测试数据:[选课表]
if object_id('[选课表]') is not null drop table [选课表]
go
create table [选课表]([sno] varchar(4),[cno] varchar(3))
insert [选课表]
select '0001','001' union all
select '0001','002' union all
select '0001','003' union all
select '0002','001' union all
select '0002','002' union all
select '0002','004' union all
select '0002','002'
SELECT s.sno ,
s.sname ,
COUNT(b.cno) [选课数量] ,
( SELECT COUNT(1)
FROM course
) [总课数]
FROM student s
RIGHT JOIN [选课表] b ON s.sno = b.sno
LEFT JOIN course c ON b.cno = c.cno
GROUP BY s.sno ,
s.sname
HAVING COUNT(b.cno)=( SELECT COUNT(1)