简体   繁体   中英

How to update single row using multiple tables?

I have 3 tables like:

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

Animals contain both data from dogs and cats and some more. Some rows from animals table have NULL address values, and I want to UPDATE it with cats and dogs address values like this:

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

But I not sure that JOIN will work fine there. How can I combine address values from both cats and dogs tables? OR I need to update it one by one?

Here is one way to phrase this:

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

Depending on your actual set-up, it might be a good idea to ensure that there is at least one match in either of the tables:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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