I have a series of tables in my database that are using DATE
as the primary key
. I would like to reconfigure the tables so that an AUTO_INCREMENT
ID field is the primary key.
What is the best way to change the tables so the first record ID
in each table start at 1 and auto_increment by 1 up to, and beyond, the latest records?
Subsequently, two of the tables do not have data going back as far as the other tables so I'd like to have their starting ID fields begin at a certain integer and auto_increment from there.
- MySQL version: 5.5.45
- Engine: MyISAM
- Interface: phpmyadmin
Best Answer
This takes one from a table that has a PK on date (or datetime, change accordingly), to a table with an auto_increment column. Then it takes a child table if you will (that relied on the previous date PK FK setup) in a new direction using the new parent table's auto_increment PK.
It could be done inline in the original tables. But I am risk adverse, and not wanting to mess up anyone's originals. At the end, do drops and renames. By the way, one interesting functionality with mysql rename is doing hot-swap renaming of tables that are safe even in high concurrency environments.
So in the below, think of
origThought
andnextThought
as the before and after of a main table. And think ofsotv1
andsotv2
as the before and after of some-other-table before and after conversion.Create the Schema
Now load some data
Complete the conversion of sotv2 table
Now we merely want to patch our new sotv2 table using appropriate newPkValue.
Well not patch it because our FK is in place, so let's try to do it all in one insert statement.
Else it will fail due to FK (which is your friend). Your foreign key constraints are your friends.
Look at results
bingo, what we want to see.
Drop the prev date residue we don't need anymore in this 'child' table
Now we have
That's even better !