类似问题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
,我如何解决此问题并以某种方式显示所有位置?
答案 0 :(得分:5)
使用LEFT OUTER JOIN
SELECT
location.id,
location.city,
state.name
FROM
location
LEFT OUTER JOIN
state ON state.id = location.state_id;