MySQL insert row on duplicate key update multiple columns

后端 未结 3 1884
情歌与酒
情歌与酒 2020-12-03 17:05

I have a table (name, date, stat1, stat2, stat3), (name, date) is the PK. When I insert rows, there will be duplicate keys, and I need to sum up th

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-03 18:03

    If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, MySQL performs an UPDATE of the old row. For example, if column a is declared as UNIQUE and contains the value 1, the following two statements have similar effect:

    INSERT INTO table (a,b,c) VALUES (1,2,3) ON DUPLICATE KEY UPDATE c=c+1;

    The equivalent update query is as below,

    UPDATE table SET c=c+1 WHERE a=1;

    If a and b column is unique, equivalent update query would be ,

    UPDATE table SET c=c+1 WHERE a=1 OR b=2 LIMIT 1;

提交回复
热议问题