Finding the next available id in MySQL

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

    If you want to select the first gap, use this:

    SELECT  @r
    FROM    (
            SELECT  @r := MIN(id) - 1
            FROM    t_source2
            ) vars,
            t_source2
    WHERE   (@r := @r + 1) <> id
    ORDER BY
            id
    LIMIT   1;
    

    There is an ANSI syntax version of the same query:

    SELECT  id
    FROM    mytable mo
    WHERE   (
            SELECT  id + 1
            FROM    mytable mi
            WHERE   mi.id < mo.id
            ORDER BY
                    mi.id DESC
            LIMIT 1
            ) <> id
    ORDER BY
            id,
    LIMIT   1
    

    however, it will be slow, due to optimizer bug in MySQL.

提交回复
热议问题