繁体   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