LEFT JOIN查询中的WHERE子句

时间:2018-12-29 03:55:31

标签: mysql null left-join isnull

因此,我希望获得所有SSC职位并获取尚未占用的职位数量。但是,我莫名其妙地陷入了where子句中。

这是我的表结构:

Position

SSC

Student

Account

这是我的查询

SELECT p.position_id, a.account_id FROM positions p LEFT JOIN ssc s ON s.position_id = p.position_id AND s.removed = 0 LEFT JOIN students stud ON stud.students_id = s.students_id LEFT JOIN accounts a ON a.account_id = stud.account_id WHERE p.user_level_id = 6 AND p.removed = 0

实际结果是这样:

Result

预期结果仅显示account_id中为NULL的字段。但是,如果我在查询中包含AND a.account_id = NULL,则结果为空。如果我将查询更改为:

SELECT p.position_id, a.account_id FROM positions p LEFT JOIN ssc s ON s.position_id = p.position_id AND s.removed = 0 LEFT JOIN students stud ON stud.students_id = s.students_id LEFT JOIN accounts a ON a.account_id = stud.account_id AND a.account_id = NULL WHERE p.user_level_id = 6 AND p.removed = 0

然后所有帐户ID都为NULL

1 个答案:

答案 0 :(得分:3)

没有一个=的{​​{1}}值。使用NULL

IS NULL

您可以在https://dev.mysql.com/doc/refman/8.0/en/working-with-null.html上了解有关此内容的更多信息。您可能更喜欢使用空字符串或默认值a.account_id IS NULL