我有三个表,想要在表A和B匹配上加入它们(内连接),但是,如果A中的ID不匹配,我想将它与表C匹配。像这样:
表A person
id person
1 John
2 Adam
3 Carolin
表B pet
owner_id pet
1 Bubbles
3 Fido
表C vehicle
owner_id vehicle
2 Mustang
3 Golf
我期望的结果是
person pet/vehicle
1 Bubbles
2 Mustang
3 Fido
对于第3个人来说,选择宠物而不是车辆,因为宠物不是空的。
我当然可以这样做:
select a.person,b.pet,c.vehicle from person a
join pet b on a.id = b.owner_id
join vehicle c on a.id = c.owner_id
但这会给我三列,我需要两列。
答案 0 :(得分:2)
您可以将LEFT JOIN
与COALESCE
:
select a.person, coalesce(b.pet, c.vehicle) as 'pet/vehicle'
from person a
left join pet b on a.id = b.owner_id
left join vehicle c on a.id = c.owner_id