简体   繁体   English

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

[英]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:所以:

  1. Select from courses .courses选择。
  2. Limit to the desired category.限制为所需的类别。
  3. Limit to courses not in the set of courses taken by the user.仅限于不在用户所修课程集中的课程。

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.

相关问题 SQL查询:列出一个表中未出现在另一个表中的所有项 - SQL query: list all items in one table that do not appear in another table 硬SQL查询-在另一个表中没有匹配项或在另一个表中没有发布的项目的行 - Hard SQL query - Rows with no matching in another table OR with items not published in another one 列出一个表中不在另一个表中的所有项目 - list all items from one table that are not in another SQL:当语法不相同时,如何从一个表中查询不在另一个表中的项? - SQL: How to query items from one table that are not in another when the syntax is not the same? 一个SQL查询可从另一张表中引用的不同表中获取项目数 - One SQL Query to get number of items from different tables reference in another table MS ACCESS 查询联结表,用于一个表中的所有项目,但不在另一个表中 - MS ACCESS Query with junction table, for all items in one table, but not in another 从一个表到另一个表的SQL更新查询 - SQL Update Query From one Table to another 用于查询一个或另一个表的SQL查询 - SQL query for joining one or another table SQL / MYSQL-通过一个表中的项目在另一个表中的作用来过滤它们 - SQL/MYSQL - Filtering items in one table by their effects in another table SQL查询,如何从一个列表中获取所有元素,而从另一表中仅获取相似元素 - SQL Query, how to get all elements from one list and only the similar ones from another table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM