I’ve added a field to a MySQL table. I need to populate the new column with the value from another table. Here is the query that I’d like to run:
UPDATE table1 t1
SET t1.user_id =
(
SELECT t2.user_id
FROM table2 t2
WHERE t2.usr_id = t1.usr_id
)
I ran that query locally on 239K rows and it took about 10 minutes. Before I do that on the live environment I wanted to ask if what I am doing looks ok i.e. does 10 minutes sound reasonable. Or should I do it another way, a php loop? a better query?
Use an
UPDATE JOIN! This will provide you a nativeinner jointo update from, rather than run the subquery for every bloody row. It tends to be much faster.Ensure that you have an index on each of the
usr_idcolumns, too. That will speed things up quite a bit.If you have some rows that don’t match up, and you want to set
t1.user_id = null, you will need to do aleft joinin lieu of aninner join. If the column isnullalready, and you’re just looking to update it to the values int2, use aninner join, since it’s faster.I should make mention, for posterity, that this is MySQL syntax only. The other RDBMS’s have different ways of doing an
update join.