繁体   English   中英

SQL 查询 - 一个表中而不是另一个表中的项目列表

[英]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 和课程类别,该用户尚未参加该类别中的哪些课程

(顺便说一下,这应该在请求中。)

所以:

  1. courses选择。
  2. 限制为所需的类别。
  3. 仅限于不在用户所修课程集中的课程。

查询:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM