【问题标题】:MySQL Join with WHERE and null valuesMySQL Join 与 WHERE 和空值
【发布时间】:2013-04-09 15:16:35
【问题描述】:

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

还没有信息行的“John” Person 行也应该包含在结果中,但它没有。

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

【问题讨论】:

    标签: mysql join null where


    【解决方案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)           ║
    ╚═══════╩════╩═════════╩═══════════╩══════════════════╝
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-26
      • 1970-01-01
      • 2014-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-03
      • 2011-06-28
      相关资源
      最近更新 更多