Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorter query approach

Both source and destination tables have about 40 columns. No. of rows to be updated is about 20. Row count of Destination table is around 30k.

Is there a better (shorter query) approach to below?

UPDATE destination_table t1
SET 
field1 = (select field1 from src_table t2 where t2.pk = t1.pk),
field2 = (select field2 from src_table t2 where t2.pk = t1.pk),
... 
field40 = (select field40 from src_table t2 where t2.pk = t1.pk),
WHERE EXISTS (select 1 from src_table t2 where t2.pk = t1.pk)
like image 242
Sam P Avatar asked Mar 01 '26 18:03

Sam P


1 Answers

You could use something like this:

UPDATE      dest
SET         dest.Field1 = src.Field1,
            dest.Field2 = src.Field2,
            dest.Field3 = src.Field3,
            dest.Field4 = src.Field4,
            dest.Field5 = src.Field5,
            dest.Field6 = src.Field6
FROM        destination_table dest
INNER JOIN  src_table src
ON          src.pk = dest.pk

You just need to add in the extra fields to update.

like image 184
Kev Ritchie Avatar answered Mar 03 '26 09:03

Kev Ritchie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!