MySQL从表中获取丢失的ID
2021-11-20 00:00:00
mysql
我在 MySQL 中有这个表,例如:
I have this table in MySQL, for example:
ID | Name
1 | Bob
4 | Adam
6 | Someguy
如果您注意到,没有 ID 号(2、3 和 5).
If you notice, there is no ID number (2, 3 and 5).
如何编写查询以便 MySQL 仅回答缺少的 ID,在本例中为:2,3,5"?
How can I write a query so that MySQL would answer the missing IDs only, in this case: "2,3,5" ?
推荐答案
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/
相关文章