简体   繁体   中英

MySQL auto increment and select count

I am having a strange issue with MySQL Query, i am having a table with the fields

slno,mobileno , contractor with slno as primary key and auto increment sequence 1

, while test say uptil 100 records the count and the autoincrement values are same ,

so i truncated the table to reset the autoincrement and inserted a huge excel file with around 40k data via php, then issued select query which yields

the max of slno is 40000 as expected but the count shows 39920

, I am just amused and tried to find over google , may be my lack of keyword search ability prevented me from finding result, so i am posting in here, for ref added screen shot, Any ideas and clarifications. Thanks

在此处输入图片说明

EDIT: min slno is 1

在此处输入图片说明

EDIT : A related question with solution to find gap in auto number in mysql has been asked and solved here .

There are specific cases in which auto-incremented values can be lost. One example is if you roll back an insertion. As per the doco :

"Lost" auto-increment values and sequence gaps

In all lock modes (0, 1, and 2), if a transaction that generated auto-increment values rolls back, those auto-increment values are "lost". Once a value is generated for an auto-increment column, it cannot be rolled back, whether or not the "INSERT-like" statement is completed, and whether or not the containing transaction is rolled back. Such lost values are not reused. Thus, there may be gaps in the values stored in an AUTO_INCREMENT column of a table.

In that case, although the insert is backed out, the auto-increment may not be. That would certainly allow for the possibility that your bulk insertion from Excel is occasionally failing and retrying, with the subsequent retry working. It really depends on how your insertion process works.


In any case, assuming those values will always be contiguous is actually a bad assumption to make.

This is because, even if insertions were guaranteed to be contiguous, it's possible to delete rows which would result in gaps appearing. You can certainly fix this each time you delete (or bulk insert for that matter) but the workload is high - you basically have to find gaps and then "move" higher entries into those gaps.

This movement is likely to be non-trivial as it's most likely that there will be other tables holding key look-ups to that column, and each of those will need to be changed as well.

So the best use case for an auto-increment field is simply to provide a unique identifier for the row where no other one exists and not to be necessarily contiguous.

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