Finding the next available id in MySQL

前端 未结 15 1835
予麋鹿
予麋鹿 2020-11-29 00:50

I have to find the next available id (if there are 5 data in database, I have to get the next available insert place which is 6) in a MySQL database. How can I do that? I h

15条回答
  •  囚心锁ツ
    2020-11-29 01:35

    As I understand, if have id's: 1,2,4,5 it should return 3.

    SELECT t1.id + 1
    FROM theTable t1
    WHERE NOT EXISTS (
        SELECT * 
        FROM theTable t2
        WHERE t2.id = t1.id + 1
    )
    LIMIT 1
    

提交回复
热议问题