Insert and set value with max()+1 problems

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

    SELECT MAX(col) +1 is not safe -- it does not ensure that you aren't inserting more than one customer with the same customer_id value, regardless if selecting from the same table or any others. The proper way to ensure a unique integer value is assigned on insertion into your table in MySQL is to use AUTO_INCREMENT. The ANSI standard is to use sequences, but MySQL doesn't support them. An AUTO_INCREMENT column can only be defined in the CREATE TABLE statement:

    CREATE TABLE `customers` (
      `customer_id` int(11) NOT NULL AUTO_INCREMENT,
      `firstname` varchar(45) DEFAULT NULL,
      `surname` varchar(45) DEFAULT NULL,
      PRIMARY KEY (`customer_id`)
    )
    

    That said, this worked fine for me on 5.1.49:

    CREATE TABLE `customers` (
      `customer_id` int(11) NOT NULL DEFAULT '0',
      `firstname` varchar(45) DEFAULT NULL,
      `surname` varchar(45) DEFAULT NULL,
      PRIMARY KEY (`customer_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1$$
    
    INSERT INTO customers VALUES (1, 'a', 'b');
    
    INSERT INTO customers 
    SELECT MAX(customer_id) + 1, 'jim', 'sock'
      FROM CUSTOMERS;
    

提交回复
热议问题