MySQL - LEFT JOIN并从表中选择行而不是另一个

时间:2012-07-23 08:53:33

标签: mysql select join compare

好的,所以这里有一个现有的查询,它可以满足我的需要。

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'为索引。我还有另一个表“注册”,其中包含用户注册哪些培训课程有3列的信息:'id' - 索引,'user_id' - 注册培训的用户的ID,以及'course_id' - 培训课程的ID。

除了我现有的查询之外,我还需要做的是,只选择那个用户已经没有“注册”行的培训课程。

我希望这是有道理的。感谢谁能提供帮助。我试了几个小时。该查询对我来说太大了,无法保持井井有条并正确思考如何做到这一点。

1 个答案:

答案 0 :(得分:6)

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返回。