sQL语句求解释 答案中join不懂
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.学号>=2
3.关联学生表,得到姓名和学号:
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 @class select 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 );
这就是以错的 连接出错
第二张表和第三张表的外键关系是课程号 所以 on后面是bc.课程号id
select stu.id ,stu.name from student stu
left join choice cho on stu.id = cho.stu_id
left join project pro on pro.id = cho.pro_id
wherre cho.id = 'c01' and cho.id='c02'