[英]SQL query: list all items in one table that do not appear in another table
[英]SQL query - list of items in one table not in another
我需要一些有关 SQL 查询的帮助。 我有一个课程表和一个包含用户 ID 和课程 ID 的表,表示用户已参加的课程(可能没有参加任何课程;该用户 ID 在该表中没有条目)。
我需要一个查询来返回未参加的课程列表。
Course Category table
CategoryID
Caegory
Courses table
CourseID
CategoryID
CourseName
...
UserCourse table
UserID
CourseID
你可以使用not exists
Select *
From Courses c
Where Not Exists (Select 1 From UserCourse uc Where uc.CourseID = c.CourseID)
这只会列出课程
select *
from Courses C
Left join CourseCategory cc on
cc.CategoryID = c.CategoryID
where CourseID not in (Select CourseID from UserCourse where UserID = 14)
我需要的是对于给定的用户 ID 和课程类别,该用户尚未参加该类别中的哪些课程
(顺便说一下,这应该在请求中。)
所以:
courses
选择。查询:
select *
from courses
where categoryid = 123
and courseid not in (select courseid from usercourse where userid = 456);
另一种编写相同查询的方法,它将执行得更快。
select C.CourseID,C.CategoryID
from Courses C
Left join CourseCategory cc on
cc.CategoryID = c.CategoryID
left join UserCourse uc
on C.CourseID=uc.CourseID
where uc.CourseID is null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.