MySQL - 使用NULL值连接表时没有结果

时间:2010-09-23 17:04:17

标签: mysql

类似问题here,但这有点不同......

我想加入两个表:

location
---------------------------
| id | city    | state_id |
---------------------------
| 1  | Denver  |        6 |
| 2  | Phoenix |        2 |
| 3  | Seattle |     NULL |
---------------------------

state
-------------------
| id | name       |
-------------------
| 1  | Alabama    |
| 2  | Alaska     |
| 3  | Arizona    |
| 4  | Arkansas   |
| 5  | California |
| 6  | Colorado   |
-------------------

SELECT
    location.id,
    location.city,
    state.name
FROM
    location
JOIN
    state ON state.id = location.state_id;

但是,在location.state_id恰好是NULL的情况下(可能输入数据的人忘记选择状态),查询不会返回结果,但这并不意味着该位置不存在。

即使state_id可能是NULL,我如何解决此问题并以某种方式显示所有位置?

1 个答案:

答案 0 :(得分:5)

使用LEFT OUTER JOIN

SELECT
location.id,
location.city,
state.name
FROM
    location
LEFT OUTER JOIN
    state ON state.id = location.state_id;