慕盖茨4494581
join两个选课表,如果学生选了2个及以上的课程,得到的数据是翻n倍的,答案不对,至少不完整。 正常思路:1.得到所有包含C01、C02课程的选课:select A.学号,B.课程名 from 选课表 as A join 课程表 as B on A.课程号=B.课程号 where B.课程名 in ('C01','C02')order by A.学号2.得到同时包含C01、C02课程名的学号: select A.学号 from 选课表 as A join 课程表 as B on A.课程号=B.课程号 where B.课程名 in ('C01','C02')
group by A.学号 having count(A.学号>=23.关联学生表,得到姓名和学号:select C.姓名,C.学号 from 学生表 as C where C.学号 in ( select A.学号 from 选课表 as A join 课程表 as B on A.课程号=B.课程号where B.课程名 in ('C01','C02')
group by A.学号 having count(A.学号>=2) 测试SQL:-- 学生表declare @student table(id int identity(1,1),name nvarchar(20),sex bit default(0),depart nvarchar(20) default '',age int default 18);-- 选课表declare @course table(studentid int,classid int,grade int default 100);-- 课程表declare @class table(cid int identity(1,1),cname nvarchar(20),ccredit int default 100);-- 8个学生记录insert into @student(name) values('a'),('b'),('c'),('d'),('e'),('f'),('g'),('h');-- 6门课程insert into @class(cname) values('C01'),('C02'),('C03'),('C04'),('C05'),('C06');-- 12门课程insert into @course(studentid,classid) values(1,1),(1,2),(1,3),(2,1),(2,2),(3,1),(4,2),(5,3),(6,1),(7,1),(8,2),(8,3)--select * from @student--select * from @course--select * from @classselect c.id,c.name from @student as c where c.id in ( select a.studentid from @course as a inner join @class as b on a.classid=b.cid where b.cname in ('C01','C02')
group by a.studentid having count(a.studentid)>=2);