Finding the next available id in MySQL

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

    If you really want to compute the key of the next insert before inserting the row (which is in my opinion not a very good idea), then I would suggest that you use the maximum currently used id plus one:

    SELECT MAX(id) + 1 FROM table
    

    But I would suggest that you let MySQL create the id itself (by using a auto-increment column) and using LAST_INSERT_ID() to get it from the DBMS. To do this, use a transaction in which you execute the insert and then query for the id like:

    INSERT INTO table (col1) VALUES ("Text");
    SELECT LAST_INSERT_ID();
    

    The returnset now contains only one column which holds the id of the newly generated row.

    0 讨论(0)
  • 2020-11-29 01:51

    It's too late to answer this question now, but hope this helps someone.

    @Eimantas has already given the best answer but the solution won't work if you have two or more tables by the same name under the same server.

    I have slightly modified @Eimantas's answer to tackle the above problem.

    select Auto_increment as id from information_schema.tables where table_name = 'table_name' and table_schema = 'database_name'
    
    0 讨论(0)
  • 2020-11-29 01:51

    This worked well for me (MySQL 5.5), also solving the problem of a "starting" position.

    SELECT
        IF(res.nextID, res.nextID, @r) AS nextID
    FROM
        (SELECT @r := 30) AS vars,
        (
        SELECT MIN(t1.id + 1) AS nextID
        FROM test t1
        LEFT JOIN test t2
          ON t1.id + 1 = t2.id
        WHERE t1.id >= @r
          AND t2.id IS NULL
          AND EXISTS (
              SELECT id
              FROM test
              WHERE id = @r
          )
      LIMIT 1
      ) AS res
    LIMIT 1
    

    As mentioned before these types of queries are very slow, at least in MySQL.

    0 讨论(0)
提交回复
热议问题