Insert and set value with max()+1 problems

后端 未结 11 1200
难免孤独
难免孤独 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: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.

提交回复
热议问题