I’m trying to build an script for a database migration and I have a doubt. I have a table which has lots of registers and an integer type key. This key is auto incremental and now beginning with the ‘1’ index.
The problem is that this index has to be occupied by a default value in the new database. So I want to loop database rows to get each index incremented in one, to leave the first place in blank and insert my value into it. I have tried with this statement:
UPDATE `tapp`, (
SELECT @loop := id_App
FROM
tapp
) o
SET id_App = id_App + 1;
However, is trying to update each index starting from the beginning, so when it tries converting the first one to ‘2’ it finds out the second one is already taken and can’t make it.
It’s important to make the increase in one, because it’s a MyIsam database and I also have to update each foreign key one by one. I’m using MySQL.
Please give me a hand!
The easiest way is twofold: After inserting everything into the target table, you make a 2-pass update.
First, you check what the highest number is in the table, then increment it by one and remember it as topnumber.
Then, you update everything to incremental numbers, starting with topnumber. Finally, you update everything, starting with whatever your initial seed is and increment by one each record.
topnumber becomes 11
After the first pass, the data looks like this:
After the second pass (and assuming your initial number is 7), the data looks like this:
UPDATE
Alternatively, instead of updating the numbers to incremental values, you could add the remembered top number to every initial value at the first pass (and so the above sample table would look like this after the first update:
), and at the second pass, you would decrement all the numbers by the previously stored top number and increment them by 1, which, for our example, would result in the following:
Using the names in your code snippet, the entire script might look something like this: