简体   繁体   中英

mysql - copy IDs from one table to another for first n rows

I have 2 tables:

table1:

shareID |    shareName
__________________

1         shareA
2         shareB
3         shareC

table2:

shareID |    shareName
__________________

0         shareA
0         shareA
0         shareB
0         shareC

I need to copy the shareID from table1 to table2 for the matching shareName.

I have this query which works

UPDATE table1, table2 SET table2.shareID=table1.shareID WHERE table2.shareName=table1.shareName

But the problem is that table2 has ~600K rows, and table1 about 350. So with the query about this takes too long.

Originally I thought it wouldn't work due to memory constraints, but as I was writing this question, the query completed and I have what I need. Took about 5 mins maybe more. But I'd like to know if there is a better way to do this?

Thanks

Simply use a join :

UPDATE table1 t1 JOIN
       table2 t2
       ON t2.shareName = t1.shareName
    SET t2.shareId = t1.shareID ;

Then, add an index:

create index idx_table1_shareName on table1(shareName);

Actually, I'm not sure which table is better for the index (I'm confused by the fact that the table names in your query differ from the names in the question). So, build one on both tables:

create index idx_table2_shareName on table2(shareName);

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