简体   繁体   中英

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.

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,

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.

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. But in that case I'm pretty sure it would be more efficient to rebuild the table.

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