我目前正在努力解决一个(我认为相当容易)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
我的查询部分不应该解决这个问题吗?该行不包括在内。我还缺少其他东西吗?