在经典sql50题中这道题是这样的:
有三张表
student表
course表
score表
#10、查询学过编号为"01"但是没有学过编号为"02"的课程的同学的信息
这是网上查的
select st.* from student st inner join score sc on sc.s_id = st.s_id inner join course c on c.c_id=sc.c_id and c.c_id="01" where st.s_id not in ( select st2.s_id from student st2 inner join score sc2 on sc2.s_id = st2.s_id inner join course c2 on c2.c_id=sc2.c_id and c2.c_id="02" )
这是我自己写的(单纯觉得这样看上去清楚一点,然后就懒得跟课程表连了,有成绩的话他就学了,没有成绩他就没学)
第一种方法就是用IN然后用学生表中s_id跟成绩表中条件是02课程的s_id 进行比较
SELECT t1.* FROM student t1 JOIN (SELECT s_id FROM score WHERE c_id =01 and s_id NOT in (SELECT s_id FROM score WHERE c_id =02)) t2 ON t1.s_id = t2.s_id
第二种方法就是
用学习01课程的表左连接学习02课程的表查询出来s_id,因为是左连接学过01但没有学过02的人他的那个成绩就是用NULL显示
根据这个NULL进行判断。如果是NULL他就是学过01但没学过02的。
SELECT t1.* FROM student t1 JOIN (SELECT t1.s_id FROM (SELECT s_id,s_score FROM score WHERE c_id =01) t1 LEFT JOIN (SELECT s_id,s_score
FROM score
WHERE c_id =02) t2 ON t1.s_id = t2.s_id WHERE t2.s_score IS NULL) t2 ON t1.s_id = t2.s_id
查出来结果都是一样的
记录一下哈哈