Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

sql - mysql delete,autoincrement

I have a table in MySQL using InnoDB and a column is there with the name "id".

So my problem is that whenever I delete the last row from the table and then insert a new value, the new value gets inserted after the deleted id.

I mean suppose my id is 32, and I want to delete it and then if I insert a new row after delete, then the column id auto-increments to 33. So the serial format is broken ie,id =30,31,33 and no 32.

So please help me out to assign the id 32 instead of 33 when ever I insert after deleting the last column.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Short answer: No.

Why?

  1. It's unnecessary work. It doesn't matter, if there are gaps in the serial number.
  2. If you don't want that, don't use auto_increment.
  3. Don't worry, you won't run out of numbers if your column is of type int or even bigint, I promise.
  4. There are reasons why MySQL doesn't automatically decrease the autoincrement value when you delete a row. Those reasons are
    • danger of broken data integrity (imagine multiple users perform deletes or inserts...doubled entries may occur or worse)
    • errors may occur when you use master slave replication or transactions
    • and so on ...

I highly recommend you don't waste time on this! It's really, really error prone.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...