2013-04-09 67 views
0

我目前正在努力(很容易,我認爲)的SQL問題,但我似乎無法弄清楚。MySQL加入WHERE和空值

假設我有以下表格:

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 | 
+----------+----+-----------+---------------------------------------------------+ 

如果我想的個人表和信息(類型=人)的一個子集,我的查詢會是這樣的:

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 | 
+-------+----+----------+----+-----------+------------------+ 

的「約翰」的人行,誰不尚未有一個信息行,也應包括在結果,但事實並非如此。

我在做什麼錯?我的查詢的OR Information.type IS NULL部分不應該照顧這個嗎?該行不包括在內。我錯過了別的嗎?

回答

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)   ║ 
╚═══════╩════╩═════════╩═══════════╩══════════════════╝ 
+0

這就是它!謝謝! – brtdv 2013-04-09 15:25:19

+0

不客氣':D' – 2013-04-09 15:25:50