MySQL syntax for inserting a new row in middle rows?

前端 未结 3 1101
广开言路
广开言路 2020-12-05 07:59

mysql sintax for insert a new row in middle rows or wherever we want without updating the existing row, but automatically increment the primary key (id)?

\'          


        
相关标签:
3条回答
  • 2020-12-05 08:26

    You can't use the autoincrement feature for the new row. The next autoincrement value will always be after the last autoincrement value generated; never an intermediate value. The only way I see to do this is rather painful: insert a new row that is a copy of the last row (to bump the autoincrement number for the table) and then update all the remaining rows (including the one you think of as the new one).

    If the values are unique, I wonder about the wisdom of using a separate id column. Why not make the value column the primary key?

    0 讨论(0)
  • 2020-12-05 08:32

    You will have to split it into 2 operations.

    START TRANSACTION;
    
    UPDATE table1 SET id = id + 1 WHERE id >= 3 order by id DESC;
    
    INSERT INTO table1 (id, value) VALUES (3, 300);
    
    COMMIT;
    

    Notice that you need the order by in the update statement, so it will start with the highest ids first.

    Another idea would be to declare id as decimal(10,1) and insert value 2.5 as id in between 2 and 3.

    0 讨论(0)
  • 2020-12-05 08:40
    insert into my_table (value)
    values (select value+100 from my_table order by id desc limit 1)
    
    0 讨论(0)
提交回复
热议问题