【问题标题】:MySQL - LEFT JOIN and select rows from table not in anotherMySQL - 左连接并从表中选择不在另一个表中的行
【发布时间】:2023-03-03 16:40:04
【问题描述】:

好的,这是我现有的查询,可以满足我的需要。

SELECT C1.id AS id, C1.title AS title, C1.instructor_id AS instructor_id, 
  C1.description AS description, C1.date AS date, C1.starttime AS starttime, 
  C1.endtime AS endtime, C1.training_id AS training_id, C2.name AS name, 
  C2.id AS instructors_id 
FROM trainings C1 
LEFT JOIN instructors C2 ON C1.instructor_id = C2.id

但是,我需要添加一些内容。除了我拥有的表之外,我还有两张表需要比较。

“培训”表有一个培训课程列表,由“id”索引。我还有另一个表“registrations”,其中包含有关哪些用户注册了哪些培训课程的信息,包含 3 列:“id” - 索引,“user_id” - 注册培训的用户的 ID,以及“course_id” - 培训课程的 ID。

除了我现有的查询之外,我还需要做的是仅选择在该用户的“注册”中没有一行的培训课程。

我希望这是有道理的。谢谢谁能帮忙。我已经尝试了几个小时。查询太大了,我无法保持井井有条并正确思考如何去做。

【问题讨论】:

    标签: mysql select join compare


    【解决方案1】:
    SELECT C1.id AS id, C1.title AS title, C1.instructor_id AS instructor_id, 
      C1.description AS description, C1.date AS date, C1.starttime AS starttime, 
      C1.endtime AS endtime, C1.training_id AS training_id, C2.name AS name, 
      C2.id AS instructors_id 
    FROM trainings C1 
    LEFT JOIN instructors C2 ON C1.instructor_id = C2.id
    LEFT JOIN registrations C3 ON < Whatever they're connected on >
    WHERE C3.id IS NULL
    

    基本上也只是JOIN,并通过WHERE ... IS NULL 对其进行过滤,因为LEFT JOIN 将作为NULL 返回连接表的列。

    【讨论】:

    • 好的,对不起,如果我只是不理解。 (我一整天都在工作,所以我的脑力很低。这个网站的截止日期是早上,这是最后一件事。)好吧,假设当前登录的用户 ID 是 3。我需要从“trainings”表中获取“registrations”表中没有“user_id”列中“3”的行的所有行。因此,假设我在“培训”中有 3 个整体,ID 为 1、2 和 3。让我们说在“注册”表中,我有 2 个整体,用户 ID 为“3”,“1”和“3” ' 作为 course_id,我只想要返回 id 为 '2' 的行。
    • 希望一切都能解决。只需尝试加入registrations,就像您想要该数据一样,然后添加WHERE
    猜你喜欢
    • 1970-01-01
    • 2018-03-30
    • 2015-06-19
    • 2012-07-30
    • 2020-03-21
    • 2011-05-17
    • 2019-05-26
    相关资源
    最近更新 更多