简体   繁体   English

将MySQL列从VARCHAR迁移到另一个表中的外键的最有效方法

[英]Most efficient way to migrate a MySQL column from a VARCHAR to a foreign key in another table

I have a few huge (10s of millions of rows in 1 table) legacy tables that have a few columns I should definitely have set up to be foreign keys when I created them, but without a time machine, I have to migrate them. 我有一些巨大的旧表(在1个表中有千万行),这些表有几列,我在创建它们时肯定应该将它们设置为外键,但是如果没有时间机器,我就必须迁移它们。

What's in these columns is like a short "key" for something else. 这些列中的内容就像是其他内容的短“键”。 A real example of one of these new tables would be: 这些新表之一的真实示例为:

+----+-----+---------+
| id | key |  name   |
+----+-----+---------+
|  1 | bf  | BetFair |
|  2 | bd  | BetDaq  |
+----+-----+---------+

And a current row, in the current table has something like, 在当前表中的当前行有类似的内容,

. (bet_id=1234, odds=2.1, source='bf') (bet_id=1235, odds=2.15, source='bd') .

And what I want the eventual outcome to be, 我希望最终的结果是

. (bet_id=1234, odds=2.1, source_id=1) (bet_id=1235, odds=2.15, source_id=2) .

I know how to do this in multiple steps, create the new tables, add all the data from the source tables to the new tables with GROUP BY / DISTINCT , and eventually setting the new foreign key id columns with commands like, 我知道如何分多个步骤进行操作,创建新表,使用GROUP BY / DISTINCT将源表中的所有数据添加到新表中,并最终使用以下命令设置新的外键ID列:

UPDATE BetsTable SET source_id=1 WHERE source='bf' , UPDATE BetsTable SET source_id=1 WHERE source='bf'

I'm just wondering if there's more of a "one-shot", efficient SQL command to update the entire table in one step, rather than multiple. 我只是想知道是否还有更多的“一次性”高效SQL命令可以一步更新整个表,而不是多次更新。

If you just want to change the data, try this: 如果您只想更改数据,请尝试以下操作:

UPDATE BetsTable b
JOIN NewTable n ON n.key = b.source
SET b.source = n.id

If you realy need to make the source column a foreign key, you will need to change it's data type first. 如果确实需要将source列设置为外键,则需要首先更改其数据类型。 But in that case I'm pretty sure it would be more efficient to rebuild the table. 但是在那种情况下,我很确定重建表会更有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM