HOWTO: MySQL - Update Data in one table from another table
I have just been refactoring a legacy database and needed to update some data in one table from another table in MySQL.
In this case the 2 tables had the same values for the identity colomn.
Syntax:
UPDATE tablename1 t1 SET colomn1 = (SELECT colomn1 from tablename2 t2 WHERE t1.id = t2.id);
For example
If i had tables: ‘products’ and ‘merchandise’ and needed to copy the product title into the merchandise title colomn, I would simply:
UPDATE merchandise m SET title = (SELECT title from products p where m.id = p.id);

June 5th, 2009 at 4:42 am
This is interesting. However, I tried to use join between two tables to update. But one of the table having large number of records (more than 1 mio). It seem takes a whole life for the statement to execute. Should the statement you provided take shorter time execution? Haven’t tried yet though.
June 10th, 2009 at 2:10 am
Thanks, this was great!
September 12th, 2009 at 7:13 pm
Great! It’s works perfect for me. Thanks a lot.