On Duplicate Key Update - Multiple Columns

后端 未结 4 1906
谎友^
谎友^ 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 14:44

    INSERT INTO table1
      (`col1`, `col2`, `col3`, `col4`)
    VALUES
      ('val1', 'val2', 'val3', 'val4')
    ON DUPLICATE KEY UPDATE
      `col2`='val2',
      `col3`='val3', [...]
    

    I fixed your quotes and tickmarks.

    Edit:

    In PHP:

    $result = mysql_query("
         INSERT INTO table1
             (col1, col2, col3, col4)
         VALUES
             ('" . $val1 . "',  '" . $val2 . "', '" . $val3 . "', '" . $val4 . "')
         ON DUPLICATE KEY UPDATE
             col2='" . $val2 . "',
             col3='" . $val3 . "',
             col4='" . $val4 . "'"
     );
    

    Note that the values are surrounded by single quotation marks '. If the values are a number type (INT, FLOAT, etc) you can drop those quotation marks. Backticks are optional around the column names as long as you are not using column names like count, type, or table.

    In the PHP example, string concatenation is used to clearly separate out the variables.

提交回复
热议问题