[英]SQL query - list of items in one table not in another
I need some help with a SQL query.我需要一些有关 SQL 查询的帮助。 I have a table of courses and a table that contains user id and course id, denoting courses that user has taken (might not have taken any; no entry in that table for that user id).我有一个课程表和一个包含用户 ID 和课程 ID 的表,表示用户已参加的课程(可能没有参加任何课程;该用户 ID 在该表中没有条目)。
I need a query to return the list of courses not taken.我需要一个查询来返回未参加的课程列表。
Course Category table
CategoryID
Caegory
Courses table
CourseID
CategoryID
CourseName
...
UserCourse table
UserID
CourseID
you can use not exists
你可以使用not exists
Select *
From Courses c
Where Not Exists (Select 1 From UserCourse uc Where uc.CourseID = c.CourseID)
This will just list the course这只会列出课程
select *
from Courses C
Left join CourseCategory cc on
cc.CategoryID = c.CategoryID
where CourseID not in (Select CourseID from UserCourse where UserID = 14)
what i need is for a given user id and course category, what courses within that category have not been taken by this user我需要的是对于给定的用户 ID 和课程类别,该用户尚未参加该类别中的哪些课程
(This should have been in the request by the way.) (顺便说一下,这应该在请求中。)
So:所以:
courses
.从courses
选择。The query:查询:
select *
from courses
where categoryid = 123
and courseid not in (select courseid from usercourse where userid = 456);
Another way of writing same query, which will perform faster.另一种编写相同查询的方法,它将执行得更快。
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.