sql--每天两道sql题,天天健康好身体_第三天
每天会在网上找两三道sql题练习练习,提高自己的sql语句的使用能力(先自己思考出答案,再和别人的答案做一下对比,然后深入思考一下)
以下是四个表信息:

问题1:查询出没有选修过“娜娜”老师课程的学生的学号和姓名
答案1:select s.sid,s.sname from student_info_table where s.sid not in ( select g.sid from grade_table g inner join(select c.cid from class_info_table c, teacher_info_table t where c.tid=t.tid and t.tname="娜娜" ) on g.cid=c.cid )
思考:哎呀,想了半天,想出来上面的方式,1)先课程表和老师信息表进行连表查询并筛选出来娜娜老师的 课程id号, 2)将这个连表的子查询的查询结果 和 成绩表进行 内连接,这样一内连就能得到 选了娜娜课程的学生的成绩信息, 3)最后查询学生信息表,并过滤出不包含步骤2中的学生id. 这样就查出来结果了。
然后看了一下之前想的方法,发现步骤2可以不用inner join 就可以,直接where 过滤不就出来了么,哎,真的是.....
select s.sid,s.sname from student_info_table as s where s.sid not in (select distinct g.sid from grade_table as g where g.cid in(select c.cid from class_info_table c, teacher_info_table t where c.tid=t.tid and t.tname="娜娜" ) on g.cid=c.cid ))
问题2:删除学习“娜娜”老师课的成绩表中的记录
答案2: delete from grade_table where cid in (select class_info_table.cid from class_info_table,teacher_info_table where class_info_table.tid=teacher_info_table.tid);
思考:先通过子查询查询娜娜老师的课程id, 然后通过过滤课程id进行删除操作。
可以给表起别名,即 delete from grade_table where cid in (select c.cid from class_info_table c,teacher_info_table t where c.tid=t.tid);
注意:一旦在from 后给表起别名后,那么其他地方就只能使用表别名,不能用表原来的名称,否则会报错
![]()

浙公网安备 33010602011771号