当前位置:Gxlcms > 数据库问题 > [MySQL练习] 查询两个表的差集(两种方法)

[MySQL练习] 查询两个表的差集(两种方法)

时间:2021-07-01 10:21:17 帮助过:201人阅读

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

查出来结果都是一样的

技术图片

 

 记录一下哈哈

[MySQL练习] 查询两个表的差集(两种方法)

标签:练习   color   成绩   经典   _id   连接   sql   结果   from   

人气教程排行