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

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

我有三张table,像:

  1. animals: id, code, address
  2. dogs: id,code, address
  3. cats: id,code, address

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

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

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

laximzn5

laximzn51#

这里有一种说法:

  1. update animals a
  2. set address = coalesce(c.address, d.address)
  3. from animals a1
  4. left join dogs d on d.id = a1.id
  5. left join cats c on c.id = a1.id
  6. where a.id = a1.id

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

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

相关问题