How do I get first unused ID in the table?

后端 未结 6 1849
温柔的废话
温柔的废话 2021-01-12 23:58

I have to write a query wherein i need to allocate a ID (unique key) for a particular record which is not being used / is not being generated / does not exist i

6条回答
  •  说谎
    说谎 (楼主)
    2021-01-13 00:28

    I named your table unused.

    SELECT  id
    FROM    (
            SELECT  1 AS id
            ) q1
    WHERE   NOT EXISTS
            (
            SELECT  1
            FROM    unused
            WHERE   id = 1
            )
    UNION ALL
    SELECT  *
    FROM    (
            SELECT  id + 1
            FROM    unused t
            WHERE   NOT EXISTS
                    (
                    SELECT  1
                    FROM    unused ti
                    WHERE   ti.id = t.id + 1
                    )
            ORDER BY
                    id
            LIMIT 1
            ) q2
    ORDER BY
            id
    LIMIT 1
    

    This query consists of two parts.

    The first part:

    SELECT  *
    FROM    (
            SELECT  1 AS id
            ) q
    WHERE   NOT EXISTS
            (
            SELECT  1
            FROM    unused
            WHERE   id = 1
            )
    

    selects a 1 is there is no entry in the table with this id.

    The second part:

    SELECT  *
    FROM    (
            SELECT  id + 1
            FROM    unused t
            WHERE   NOT EXISTS
                    (
                    SELECT  1
                    FROM    unused ti
                    WHERE   ti.id = t.id + 1
                    )
            ORDER BY
                    id
            LIMIT 1
            ) q2
    

    selects a first id in the table for which there is no next id.

    The resulting query selects the least of these two values.

提交回复
热议问题