簡體   English   中英

mysql-在前n行中將ID從一個表復制到另一個表

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

我有2張桌子:

表格1:

shareID |    shareName
__________________

1         shareA
2         shareB
3         shareC

表2:

shareID |    shareName
__________________

0         shareA
0         shareA
0         shareB
0         shareC

我需要將shareID從table1復制到table2,以獲取匹配的shareName。

我有這個查詢有效

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

但是問題是table2擁有約60萬行,而table1約有350行。因此,與此有關的查詢花費的時間太長。

本來我以為是由於內存限制而無法使用,但是當我寫這個問題時,查詢完成了,我有我需要的東西。 花了大約5分鍾的時間。 但是我想知道是否有更好的方法可以做到這一點?

謝謝

只需使用join

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

然后,添加一個索引:

create index idx_table1_shareName on table1(shareName);

實際上,我不確定哪個表最適合索引(我對查詢中的表名與問題中的表名不同感到困惑)。 因此,在兩個表上構建一個:

create index idx_table2_shareName on table2(shareName);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM