简体   繁体   中英

How to add value if exists in another table

I have table_a which has a foreign key column referencing table_b. I'd like to fill the fkey column with values from column_a if the value exists in table_b's pkid column but null if it doesn't exist.

Without looking for whether it exists, I was using the following query:

UPDATE table_a SET fkey = column_a;

That fails sometimes due to the foreign key constraint if column_a's value doesn't exist in table_b so I think I need to use some combination of CASE and EXISTS but I'm struggling with the syntax.

The constraint looks like:

ALTER TABLE table_a ADD CONSTRAINT
    constraint_fkey FOREIGN KEY (fkey) REFERENCES table_b(pkid);

Assuming the column contains null in all rows, you can join table_b on a.column_a = b.pkid :

update table_a a 
set fkey = column_a
from table_b b
where a.column_a = b.pkid

or check in a subquery whether b.pkid exists:

update table_a
set fkey = column_a
where exists (
    select pkid
    from table_b
    where pkid = column_a)

If you have to set null in appropriate rows you can use exists in case :

update table_a
set fkey = (select case
    when exists (
        select pkid
        from table_b
        where pkid = column_a)
    then column_a
    end)

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