繁体   English   中英

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

[英]How to update single row using multiple tables?

我有 3 个表,例如:

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

动物包含来自狗和猫的数据等等。 animals 表中的一些行有 NULL 地址值,我想用 cats 和 dogs 地址值更新它,如下所示:

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

但我不确定 JOIN 在那里会正常工作。 如何合并来自 cats 和 dogs 表的地址值? 或者我需要一个一个地更新它?

这是一种表达方式:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM