简体   繁体   中英

Rearrange primary keys in mysql

How to rearrange primary key column values after deleting some rows from a table in MySQL?

Foe example; a table with 4 row of data with primary key values 1,2,3,4. When delete 2nd and 3rd rows, then the key value of 4th row change to 2.

Please help me to find solution.

Why do this? You don't need to rearrange your key since it's only number, identifier for record. It has no actual meaning - so let DBMS handle that. This is a very common mistake - trying to take DBMS role.

However, I'll answer your question for common case. In MySQL you can rearrange column with:

update t cross join (select @cur:=0) as init set t.col=@cur:=@cur+1

-this, however, can't be used with column under UNIQUE (so primary key as well) restriction since during update you'll possibly get duplicate records. You should drop restriction first before do that (and create it again after update).

One method is THIS ONE .

Other then that, you can simply drop the table which is primary and then again create it. This will do the job

Why do you want to change primary keys for your data? In general this is bad idea to do that, especially when integrity contstraints comes into the game. If you need to do such thing, I would say you have bad DB desing and you should take closer look on that aspect.

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