On Duplicate Key Update - Multiple Columns

后端 未结 4 1902
谎友^
谎友^ 2020-12-08 14:34

When using insert... on duplicate key update, what is the syntax to update multiple columns?

INSERT INTO table1 (col1, col2, col3, col4) VALUES (’$val1’, ‘$v         


        
4条回答
  •  自闭症患者
    2020-12-08 15:11

    For the sake of clear syntax there's another syntax form;

    INSERT INTO `table1` SET `id`=$id,
                             `col2`='$col2',
                             `col3`='$col3'[, ...]
     ON DUPLICATE KEY UPDATE `col2`='$col2',
                             `col4`='$col4'[, ...]
    

    Example;

    INSERT INTO customers SET cid=10,
                              createdon=NOW(),
                              createdby='user',
                              cname='Steve'
      ON DUPLICATE KEY UPDATE modifiedon=NOW(),
                              modifiedby='user',
                              cname='Steve';
    

    If there does not exist a customer with ID=10 in database it will be created and columns cid, createdon, createdby, cname will be set. If it does exist, then it will be updated and columns modifiedon, modifiedbym, cname will be updated.

    NOTE#1: IF you put for primary key cid=0 here, it will fire AUTO_INCREMENT (of course, if pk column is defined as AUTO_INCREMENT) and a record will be inserted!

    NOTE#2: ON DUPLICATE KEY UPDATE makes update for existing PK ID record. But also it makes update if DUPLICATE is made on any UNIQUE KEY column. For example, if you defined that cname column is UNIQUE, then saving record with cname='Steve' that already exist will result in UPDATE of that record (not new INSERT). Take care about this because you may expect that DB returns error for UNIQUE KEY constraint violation which will not happened here.

提交回复
热议问题