简体   繁体   中英

MySQL auto increment key in table mistakes

so I created a table with a column which I declared EmployeeID as a primary key int with auto increment, but here is the problem:

If I delete a row and then insert a new one the new increment will still count For example:

ID Name
1  jayden
2  karen

delete karen...

ID Name
1 jayden

insert new one

ID Name
1 jayden
3 nicolas

So it basically skips the previous ID.

After delete a row use this query, ALTER TABLE tbl_name AUTO_INCREMENT = ID;

Actually this is how MySQL works and it's not a mistake

This is not a mistake, it is how MySQL works with auto_increment. It stores the last value which it gave at the insertion and increments it. You can always get the last ID at your next insertion

insert into yourtable(id, Name)
select id + 1, 'foo'
from yourtable
where id = (select max(id) from yourtable);

This is expected behavior from the 'delete' command What would you ever want/need an Unique Identifier that can be reaffected to someone else?

The 'Truncate' command will delete all your data and reset the ID, maybe this is what you are looking for

That's because an auto increment is a independent property of your table, that is only used when assigning new IDs and does not depend on the last existent ID on your table. This is how many relational databases, not only MySQL, were designed for.

To achieve what you want (which seems to be having IDs in sequence without "holes") you would need to query the last ID and increment on it to be set manually.

Ex:

SELECT id from Users ORDER BY id DESC LIMIT 1

Or instead setting the auto_increment of your table according to your last id.

Be aware that both of this is not performatically wise. You should really stick to the auto increment default behavior, since it's optimal, unless you have some strong reason for not doing things as they were designed to be done .

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