简体   繁体   中英

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.

For legally reasons, now I need to have another auto increment field (not auto_numeric, I will be control this manually). It fields in the firs row starts at 567.

How I can add i exists rows the new correlative number? 568 ,569, 570...

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

Just create a new int field and then update it with

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. 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.

I found the solution:

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

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