简体   繁体   English

在MySQL中重新排列主键

[英]Rearrange primary keys in mysql

How to rearrange primary key column values after deleting some rows from a table in MySQL? 从MySQL中的表中删除一些行后,如何重新排列主键列值?

Foe example; 敌人的例子; a table with 4 row of data with primary key values 1,2,3,4. 一个具有4行数据且主键值为1,2,3,4的表。 When delete 2nd and 3rd rows, then the key value of 4th row change to 2. 删除第二行和第三行时,第四行的键值将更改为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. 它没有实际意义 -因此让DBMS处理。 This is a very common mistake - trying to take DBMS role. 这是一个非常常见的错误-尝试扮演DBMS角色。

However, I'll answer your question for common case. 但是,我会回答您的常见问题。 In MySQL you can rearrange column with: 在MySQL中,您可以使用以下方法重新排列列:

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. -但是,这不能与UNIQUE (也包括主键)限制下的列一起使用,因为在更新期间您可能会得到重复的记录。 You should drop restriction first before do that (and create it again after update). 您应该先删除限制,然后再执行此操作(并在更新后再次创建)。

One method is THIS ONE . 一种方法是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. 如果您需要这样做,我会说您的数据库设计不佳,您应该在这方面进行仔细研究。

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

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