mysql find smallest + unique id available

后端 未结 7 633
忘了有多久
忘了有多久 2020-12-09 02:54

i have a column ID and something like 1000 items, some of then were removed like id=90, id=127, id=326

how can i make a query to look for those availabl

相关标签:
7条回答
  • 2020-12-09 03:17

    You can get the minimum available ID using this query:

    SELECT MIN(t1.ID + 1) AS nextID
    FROM tablename t1
       LEFT JOIN tablename t2
           ON t1.ID + 1 = t2.ID
    WHERE t2.ID IS NULL
    

    What it does is that it joins the table with itself and checks whether the min+1 ID is null or not. If it's null, then that ID is available. Suppose you have the table where ID are:
    1
    2
    5
    6

    Then, this query will give you result as 3 which is what you want.

    0 讨论(0)
提交回复
热议问题