MySQL - 当一个表中的行不存在时,继续从其他表中选择数据

时间:2015-01-15 07:21:56

标签: mysql

以下是我的两张表:

customers
--------------------
id     full_name
65     Matt Damon
64     Jimmy Kimmel
63     Guillermo

replacements
--------------------
id     customer_id    devices     reason
40     67             jumpsuit    too big
39     66             banana      too ripe
38     65             hammer      too heavy

我目前的查询是:

SELECT r.id, c.full_name, r.devices, r.reason
FROM customers c, replacements r
WHERE c.id = r.customer_id

我想要做的是继续选择查询中的其余信息,即使该行的c.full_name不存在。例如,我仍然希望它返回以下内容:

id    full_name    devices    reason
40                 jumpsuit   too big
39                 banana     too ripe
38    Matt Damon   hammer     too heavy

而不仅仅是

id    full_name    devices    reason
38    Matt Damon   hammer     too heavy

当客户表中不存在customer_id6667时。

任何允许我理解解决方案的参考或帮助都会非常有帮助。

1 个答案:

答案 0 :(得分:4)

使用left join

SELECT r.id, c.full_name, r.devices, r.reason
FROM replacements r
left join customers c on c.id = r.customer_id

请参阅this explanation of joins