How do I get first unused ID in the table?

后端 未结 6 1928
温柔的废话
温柔的废话 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:36

    are you allowed to have a utility table? if so i would create a table like so:

    CREATE TABLE number_helper (
        n INT NOT NULL
       ,PRIMARY KEY(n)
    );
    

    Fill it with all positive 32 bit integers (assuming the id you need to generate is a positive 32 bit integer)

    Then you can select like so:

    SELECT MIN(h.n) as nextID
    FROM my_table t
    LEFT JOIN number_helper h ON h.n = t.ID
    WHERE t.ID IS NULL
    

    Haven't actually tested this but it should work.

提交回复
热议问题