mysql find smallest + unique id available

后端 未结 7 653
忘了有多久
忘了有多久 2020-12-09 02:54

i have a column ID and something like 1000 items, some of then were removed like id=90, id=127, id=326

how can i make a query to look for those availabl

7条回答
  •  遥遥无期
    2020-12-09 03:12

    Given that your database is small enough, the correct answer is to not reuse your ids at all and just ensure its an auto incremented primary key. The table is a thousand records, so you can do this without any cost.

    However, if you have a table of a few million records/longer id, you will find that the accepted answer wont finish in sensible time.

    The accepted answer will give you the smallest of these values, correctly so, however, you are paying the price of not using an auto increment column, or if you have one, not using the auto increment column as the actual ID as it is intended (Like me, else I wouldn't be here). I'm at the mercy of a legacy application were the ID isn't the actual primary key is being used, and is randomly generated with a lolgorithm for no good reason, so I needed a means to replace that since upping the column range is now an extremely costly change.

    Here, it is figuring out the entire join between the entirety of t1 and t2 before reporting what the min of those joins is. In essence, you only care about the first NULL t1 that is found, regardless of whether it actually is the smallest or not.

    So you'd take the MIN out and add a LIMIT of 1 instead.

    edit : Since its not a primary key, you will also need to check for not null, since a primary key field cant be null

    SELECT t1.ID + 1 AS nextID
    FROM tablename t1
       LEFT JOIN tablename t2
           ON t1.ID + 1 = t2.ID
    WHERE t2.ID IS NULL
    AND t1.ID IS NOT NULL
    LIMIT 1
    

    This will always give you an id that you can use, its just not guaranteed to always be the smallest one.

提交回复
热议问题