Finding the next available id in MySQL

前端 未结 15 1647
予麋鹿
予麋鹿 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:26

    In addition to Lukasz Lysik's answer - LEFT-JOIN kind of SQL.
    As I understand, if have id's: 1,2,4,5 it should return 3.

    SELECT u.Id + 1 AS FirstAvailableId
    FROM users u
    LEFT JOIN users u1 ON u1.Id = u.Id + 1
    WHERE u1.Id IS NULL
    ORDER BY u.Id
    LIMIT 0, 1
    

    Hope it will help some of visitors, although post are rather old.

提交回复
热议问题