简体   繁体   中英

multi-row update table with “different” data

I think the best way to explain this is to tell you what I have.

I have two tables A and B both have columns Field1 and Field2. However Field 2 is not populated in table B

I want to populate field 2 of table B with field 2 of table A where field 1 of table A matches field 1 of table B.

something like update tableB set Field2 = tableA.field2 where tablea.field1 = tableb.field1.

The reason this may seem so odd and obscure is that I'm tyring to do an inital data load form an old database to a new one.

please let me know if you need clarification

It sounds like you just need a correlated update

UPDATE tableB b
   SET field2 = (SELECT a.field2
                   FROM tableA a
                  WHERE a.field1 = b.field1 )
 WHERE EXISTS( SELECT 1
                 FROM tableA a
                WHERE a.field1 = b.field1 );

Since every field2 in B is NULL to begin with, you may be able to skip the WHERE EXISTS (in which case rows in B that don't have a match in A would be updated with a NULL generating a bit of extra redo). But you would generally want to include that so that you only update rows where there is a match.

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