如何使用多个表更新单行?

elcex8rz  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(332)

我有三张table,像:

animals: id, code, address
dogs: id,code, address
cats: id,code, address

动物既包含狗和猫的数据,也包含更多的数据。表中的一些行有空地址值,我想用cats和dogs地址值更新它,如下所示:

UPDATE animals
SET address = coalesce(cats.address,dogs.address)
FROM dogs
left join cats on cats.id = dogs.id

但我不确定join在那里会不会奏效。如何组合cats和dogs表中的地址值?或者我需要一个一个的更新?

laximzn5

laximzn51#

这里有一种说法:

update animals a
set address = coalesce(c.address, d.address)
from animals a1
left join dogs d on d.id = a1.id
left join cats c on c.id = a1.id
where a.id = a1.id

根据实际设置,最好确保两个表中至少有一个匹配项:

update animals a
set address = coalesce(c.address, d.address)
from animals a1
left join dogs d on d.id = a1.id
left join cats c on c.id = a1.id
where a.id = a1.id and (d.id is not null or c.id is not null)

相关问题