Make auto increment fill previously deleted number [duplicate]

*爱你&永不变心* 提交于 2019-11-28 01:33:59

问题


Possible Duplicate:
Using unused primary keys

I created a table with an id column with auto increment Now when I deleted the rows with the id's 8,12,30 in that table.

Now when I insert a new record I want to insert the next record into 8 then 12 etc..

Is there a way to get MySQL auto increment to do this for me?

I tried to set autoincrement to some number, but I don't want to do it that way.


回答1:


You don't want to use an auto-incrementing column then. If you want to fill in the gaps, set it to an int column and handle the logic in stored proc or insert.

EDIT:

Since it's an int column, you can order them numerically. Just do a SELECT Ids FROM Table Order By Ids to get all of the Ids and check for the gaps in the returned dataset.

There's probably a smoother way of doing this, but you could loop the results with a cursor and compare to an INT variable that increments throughout the loop. When you find a gap (no match) - break the loop and use that INT value as your INSERT id.

I won't write your code for you, but those are some steps to get you going in the right direction. It should be a really basic bit of programming you should be able to handle.

Hope this helps.

EDIT #2:

As others have noted, your best move is to just leave the gaps. Unless there's some cap on the table as far as length and Ids MUST be 1-30 (weird), leave it alone. There's no benefit to filling in the gaps.

EDIT #3:

One more thing to consider: if you really do have to keep 1-30 for some reason, don't delete your rows. Add a column to flag each row as active or not and then just update the rows that are inactive when you need to and then flag them as active. This is VERY hacky, but your requirement is kinda hacky, so...




回答2:


http://sqlfiddle.com/#!8/3f071/1

Set @x to the smallest unused value:

SET @x = (
  SELECT MIN(t1.id+1)
  FROM      t t1
  LEFT JOIN t t2 ON t2.id = t1.id + 1
  WHERE t2.id IS NULL
);

INSERT INTO t(id) VALUES (@x);

Set @x to the smallest unused value which is in a gap, otherwise return NULL to use MySQL's autoincrement mechanism:

SET @x = (
  SELECT IF( MIN(t1.id-1) = 0, NULL, MIN(t1.id-1) )
  FROM      t t1
  LEFT JOIN t t2 ON t2.id = t1.id - 1
  WHERE t2.id IS NULL
);

INSERT INTO t(id) VALUES (@x);

Of course you have to wrap these into transactions if you don't want to shoot yourself in the foot or wherever you like.




回答3:


well AUTO_INCREMENT behaves like that. it doesn't fill any gaps on your deleted data. The best way you can do is to create a logic that will satisfy your needs (filling of gaps).



来源:https://stackoverflow.com/questions/12969161/make-auto-increment-fill-previously-deleted-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!