Insert and set value with max()+1 problems

后端 未结 11 1114
难免孤独
难免孤独 2020-12-02 16:43

I am trying to insert a new row and set the customer_id with max()+1. The reason for this is the table already has a auto_increatment on another column named id and the tabl

相关标签:
11条回答
  • 2020-12-02 17:18
    insert into table1(id1) select (max(id1)+1) from table1;
    
    0 讨论(0)
  • 2020-12-02 17:21

    Use alias name for the inner query like this

    INSERT INTO customers
      ( customer_id, firstname, surname )
    VALUES 
      ((SELECT MAX( customer_id )+1 FROM customers cust), 'sharath', 'rock')
    
    0 讨论(0)
  • 2020-12-02 17:24

    Use table alias in subquery:

    INSERT INTO customers
      ( customer_id, firstname, surname )
    VALUES 
      ((SELECT MAX( customer_id ) FROM customers C) +1, 'jim', 'sock')
    
    0 讨论(0)
  • 2020-12-02 17:27

    Correct, you can not modify and select from the same table in the same query. You would have to perform the above in two separate queries.

    The best way is to use a transaction but if your not using innodb tables then next best is locking the tables and then performing your queries. So:

    Lock tables customers write;
    
    $max = SELECT MAX( customer_id ) FROM customers;
    

    Grab the max id and then perform the insert

    INSERT INTO customers( customer_id, firstname, surname )
    VALUES ($max+1 , 'jim', 'sock')
    
    unlock tables;
    
    0 讨论(0)
  • 2020-12-02 17:28

    You can use the INSERT ... SELECT statement to get the MAX()+1 value and insert at the same time:

    INSERT INTO 
    customers( customer_id, firstname, surname )
    SELECT MAX( customer_id ) + 1, 'jim', 'sock' FROM customers;
    

    Note: You need to drop the VALUES from your INSERT and make sure the SELECT selected fields match the INSERT declared fields.

    0 讨论(0)
  • 2020-12-02 17:28

    Your sub-query is just incomplete, that's all. See the query below with my addictions:

    INSERT INTO customers ( customer_id, firstname, surname ) 
    VALUES ((SELECT MAX( customer_id ) FROM customers) +1), 'jim', 'sock')
    
    0 讨论(0)
提交回复
热议问题