Finding the next available id in MySQL

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

    In addition to Lukasz Lysik's answer - LEFT-JOIN kind of SQL.
    As I understand, if have id's: 1,2,4,5 it should return 3.

    SELECT u.Id + 1 AS FirstAvailableId
    FROM users u
    LEFT JOIN users u1 ON u1.Id = u.Id + 1
    WHERE u1.Id IS NULL
    ORDER BY u.Id
    LIMIT 0, 1
    

    Hope it will help some of visitors, although post are rather old.

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

    Given what you said in a comment:

    my id coloumn is auto increment i have to get the id and convert it to another base.So i need to get the next id before insert cause converted code will be inserted too.

    There is a way to do what you're asking, which is to ask the table what the next inserted row's id will be before you actually insert:

    SHOW TABLE STATUS WHERE name = "myTable"
    

    there will be a field in that result set called "Auto_increment" which tells you the next auto increment value.

    0 讨论(0)
  • 2020-11-29 01:27
    SELECT ID+1 "NEXTID" 
    FROM ( 
        SELECT ID from TABLE1 
        WHERE ID>100 order by ID
    ) "X" 
    WHERE not exists (
        SELECT 1 FROM TABLE1 t2
        WHERE t2.ID=X.ID+1
    ) 
    LIMIT 1
    
    0 讨论(0)
  • 2020-11-29 01:28

    One way to do it is to set the index to be auto incrementing. Then your SQL statement simply specifies NULL and then SQL parser does the rest for you.

    INSERT INTO foo VALUES (null);
    
    0 讨论(0)
  • 2020-11-29 01:31

    Update 2014-12-05: I am not recommending this approach due to reasons laid out in Simon's (accepted) answer as well as Diego's comment. Please use query below at your own risk.

    The shortest one i found on mysql developer site:

    SELECT Auto_increment FROM information_schema.tables WHERE table_name='the_table_you_want'
    

    mind you if you have few databases with same tables, you should specify database name as well, like so:

    SELECT Auto_increment FROM information_schema.tables WHERE table_name='the_table_you_want' AND table_schema='the_database_you_want';
    
    0 讨论(0)
  • 2020-11-29 01:32

    you said:

    my id coloumn is auto increment i have to get the id and convert it to another base.So i need to get the next id before insert cause converted code will be inserted too.

    what you're asking for is very dangerous and will lead to a race condition. if your code is run twice at the same time by different users, they will both get 6 and their updates or inserts will step all over each other.

    i suggest that you instead INSERT in to the table, get the auto_increment value using LAST_INSERT_ID(), and then UPDATE the row to set whatever value you have that depends on the auto_increment value.

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