MySQL加入WHERE和null值

时间:2013-04-09 15:16:35

标签: mysql join null where

我目前正在努力解决(我认为相当容易)SQL问题,但我似乎无法弄明白。

假设我有以下表格:

Persons
+-------+----+
| name  | id | 
+-------+----+
| Steve | 1  | 
| John  | 2  | 
+-------+----+

Information
+----------+----+-----------+---------------------------------------------------+
| type     | id | linked_id | info                                              |
+----------+----+-----------+---------------------------------------------------+
| persons  | 1  | 1         | Info about Steve                                  |
| cars     | 2  | 1         | Info about a car, aka not stored in Persons table |
+----------+----+-----------+---------------------------------------------------+

如果我想要Persons表和Information的一部分(type = persons),我的查询将是这样的:

SELECT * 
FROM Persons
LEFT JOIN Information ON Persons.id = Information.linked_id
WHERE (Information.type = "persons" OR Information.type IS NULL)

这应该是我的期望:

Desired Result
+-------+----+----------+------+------------+------------------+
| name  | id | type     | id   | linked_id  | info             |
+-------+----+----------+------+------------+------------------+
| Steve | 1  | persons  | 1    | 1          | Info about Steve |
| John  | 2  | NULL     | NULL | NULL       | NULL             |
+-------+----+----------+------+------------+------------------+

但这是实际结果:

+-------+----+----------+----+-----------+------------------+
| name  | id | type     | id | linked_id | info             |
+-------+----+----------+----+-----------+------------------+
| Steve | 1  | persons  | 1  | 1         | Info about Steve |
+-------+----+----------+----+-----------+------------------+

的“John”Person行也有一个Information行,也应该包含在结果中,但不是。

我做错了什么?我的查询的OR Information.type IS NULL部分不应该处理这个问题吗?但是不包括该行。我错过了别的什么吗?

1 个答案:

答案 0 :(得分:1)

您需要在加入表之前将条件放在ON子句中。

SELECT * 
FROM   Persons
       LEFT JOIN Information 
          ON Persons.id = Information.linked_id AND 
             Information.type = 'persons'

输出

╔═══════╦════╦═════════╦═══════════╦══════════════════╗
║ NAME  ║ ID ║  TYPE   ║ LINKED_ID ║       INFO       ║
╠═══════╬════╬═════════╬═══════════╬══════════════════╣
║ Steve ║  1 ║ persons ║ 1         ║ Info about Steve ║
║ John  ║  2 ║ (null)  ║ (null)    ║ (null)           ║
╚═══════╩════╩═════════╩═══════════╩══════════════════╝