当一个表没有行时加入

时间:2019-06-12 11:02:59

标签: mysql sql

我有以下查询:

SELECT u.id, u.name, u.date_registered, p.time_created 
    FROM users u JOIN 
        prospect_notes p 
        ON u.id=p.subject_id  
    WHERE u.allocated_instructors = 668
    AND p.time_created = (SELECT MAX(p2.time_created) FROM prospect_notes p2 WHERE p2.subject_id = p.subject_id)
    ORDER BY p.time_created;

我的问题是prospect_notes表中没有符合以下条件的行:

AND p.time_created = (SELECT MAX(p2.time_created) FROM prospect_notes p2 WHERE p2.subject_id = p.subject_id)

我没有结果。

相反,我希望返回users表中的所有行(在这种情况下,p.time_created可能为NULL)。

2 个答案:

答案 0 :(得分:3)

由于JOIN子句,您需要小心。大概,如果相关子查询没有匹配项,则JOIN中也没有匹配项。

因此,使用LEFT JOIN并将逻辑移至FROM子句:

SELECT u.id, u.name, u.date_registered, p.time_created 
FROM users u LEFT JOIN 
     prospect_notes p 
     ON u.id = p.subject_id LEFT JOIN
     (SELECT p2.subject_id, MAX(p2.time_created) as max_time_created
      FROM prospect_notes p2
      GROUP BY p2.subject_id
     ) p2
     ON p2.subject_id = p.subject_id AND p2.time_created = p.time_created
WHERE u.allocated_instructors = 668 
ORDER BY p.time_created;

也就是说,如果您只想要time_created中的prospect_notes,则使用更简单的查询:

SELECT u.id, u.name, u.date_registered, MAX(p.time_created)
FROM users u LEFT JOIN 
     prospect_notes p 
     ON u.id = p.subject_id 
WHERE u.allocated_instructors = 668 
GROUP BY u.id  -- okay, assuming id is unique or a primary key
ORDER BY MAX(p.time_created);

答案 1 :(得分:1)

您需要LEFT JOIN,此子句允许您在正确的表格中使用NULL值。

尝试:

SELECT u.id, u.name, u.date_registered, p.time_created 
FROM users u 
LEFT JOIN prospect_notes p 
    ON u.id=p.subject_id  
WHERE u.allocated_instructors = 668
AND p.time_created = (SELECT MAX(p2.time_created) FROM prospect_notes p2 WHERE p2.subject_id = p.subject_id)
ORDER BY p.time_created;