选择另一个表中缺少的记录的有效方法

neh*_*eha 3 sql database join

我有3张桌子.以下是结构:

  • student(id int, name varchar(20))
  • course(course_id int, subject varchar(10))
  • student_course(st_id int, course_id int) - >包含注册课程的学生的姓名

现在,我想写一个查询,找出没有注册任何课程的学生.我可以想象有多种方法可以获取这些信息.能不能让我知道哪一个是最有效的,也是,为什么.此外,如果还有其他更好的执行方式,请告诉我.

db2 => select distinct name from student inner join student_course on id not in (select st_id from student_course)

db2 => select name from student minus (select name from student inner join student_course on id=st_id)

db2 => select name from student where id not in (select st_id from student_course)
Run Code Online (Sandbox Code Playgroud)

提前致谢!!

TMS*_*TMS 9

该子查询使用,无论是not in,minus或什么的,一般是低效的.常见的方法是left join:

select name 
from student 
left join student_course on id = st_id
where st_id is NULL
Run Code Online (Sandbox Code Playgroud)

使用join是"正常"和优先解决方案.