50个SQL高级查询练习(5)

题目五、

5、查询没学过“叶平”老师课的同学的学号、姓名;

select distinct(t3.sid) as 学号, t4.sname as 学生姓名  from sc t3 ,student t4 where cid  not in 
(select t2.cid  from teacher t1 ,course t2 where t1.tid=t2.tid and t1.tname='叶平' )
and t3.sid=t4.sid ;

1、首先查询出叶平老师所教的课程编号;

 select t2.cid  from teacher t1 ,course t2 where t1.tid=t2.tid and t1.tname='叶平';

查询结果如下:

《50个SQL高级查询练习(5)》

2、然后查询出没有选中叶平老师所教的课程所有学生,注意要使用distinct;

select distinct(t3.sid) from sc t3 where cid  not in 
(select t2.cid  from teacher t1 ,course t2 where t1.tid=t2.tid and t1.tname='叶平' );、

查询结果如下:

《50个SQL高级查询练习(5)》

3、最后再和student 关联得到学生姓名;

select distinct(t3.sid) as 学号, t4.sname as 学生姓名  from sc t3 ,student t4 where cid  not in
 (select t2.cid  from teacher t1 ,course t2 where t1.tid=t2.tid and t1.tname='叶平' )
and t3.sid=t4.sid ;

4、当然,为了显示美观(本人有点强迫症)还可以以学号升序排列;

select distinct(t3.sid) as 学号, t4.sname as 学生姓名  from sc t3 ,student t4 where cid  not in 
(select t2.cid  from teacher t1 ,course t2 where t1.tid=t2.tid and t1.tname='叶平' )
and t3.sid=t4.sid  
order by t3.sid asc;

最终查询结果如下:

《50个SQL高级查询练习(5)》

    原文作者:SQL
    原文地址: https://blog.csdn.net/JIAMENGHUI/article/details/80628574
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞