简体   繁体   English

在表格中添加自动增量字段

[英]Add autoincrement field in a table

I need you save my live. 我需要你救我的命。 I have a table with a LOT of rows. 我有一张桌子,上面有很多行。 One of the fields are id, it have auto_increment. 字段之一是id,它具有auto_increment。

For legally reasons, now I need to have another auto increment field (not auto_numeric, I will be control this manually). 出于法律原因,现在我需要具有另一个自动递增字段(不是auto_numeric,我将手动控制它)。 It fields in the firs row starts at 567. 它在第一行中的字段开始于567。

How I can add i exists rows the new correlative number? 如何添加我存在的行的新相关数字? 568 ,569, 570... 568,569,570 ...

您可以编写存储过程并使用CURSOR实现所需的功能,使用游标可以迭代查询的结果并在返回的每一行上执行某些操作(在您的情况下为UPDATE语句)。

Just create a new int field and then update it with 只需创建一个新的int字段,然后使用

UPDATE table SET new_column = auto_increment_column + 567;

Of course, that will also keep all the breaks in the original column. 当然,这也将所有中断保留在原始列中。 You can drop the auto_increment field and re-add it to eliminate it. 您可以删除auto_increment字段并重新添加以消除它。 It'll take a few hours, but a life's worth it, I guess. 我想这会花几个小时,但值得一辈子。

If you really need to manually renumber the fields, you'll probably just have to go the way the previous commenters have suggested and use either PHP or cursors to loop through all the records. 如果您确实需要手动为字段重新编号,则可能只需按照以前的注释者的建议进行操作,并使用PHP或游标遍历所有记录。

I found the solution: 我找到了解决方案:

SET @pos =566; SET @pos = 566; UPDATE mytable SET field_id2 = ( SELECT @pos := @pos +1 ) ORDER BY id ASC; 更新mytable SET field_id2 =(SELECT @pos:= @pos +1)ORDER BY ID ASC;

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

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