一尘不染

MySQL从表中丢失ID

mysql

我在MySQL中有此表,例如:

ID | Name
1  | Bob
4  | Adam
6  | Someguy

如果您注意到,则没有ID号(2、3和5)。

如何编写查询,以便MySQL仅回答缺少的ID,在这种情况下为“ 2,3,5”?


阅读 327

收藏
2020-05-17

共1个答案

一尘不染

SELECT a.id+1 AS start, MIN(b.id) - 1 AS end
    FROM testtable AS a, testtable AS b
    WHERE a.id < b.id
    GROUP BY a.id
    HAVING start < MIN(b.id)

希望此链接也对http://www.codediesel.com/mysql/sequence-gaps-in-
mysql/有帮助

2020-05-17