0

我目前正在努力解决一个(我认为相当容易)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 表和信息子集(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 |
+-------+----+----------+----+-----------+------------------+

还没有信息行的“约翰”人行也应该包含在结果中,但事实并非如此。

我究竟做错了什么?OR Information.type IS NULL我的查询部分不应该解决这个问题吗?该行不包括在内。我还缺少其他东西吗?

4

1 回答 1

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)           ║
╚═══════╩════╩═════════╩═══════════╩══════════════════╝
于 2013-04-09T15:17:47.063 回答