Finding the next available id in MySQL

前端 未结 15 1847
予麋鹿
予麋鹿 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.

提交回复
热议问题