MySQL insert row on duplicate key update multiple columns

后端 未结 3 1756
情歌与酒
情歌与酒 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 17:44
    INSERT INTO tb (name, date, stat1, stat2, stat3)
    VALUES (?, ?, ?, ?, ?)
    ON DUPLICATE KEY UPDATE stat1 = stat1 + VALUES(stat1), stat2 = stat2 + VALUES(stat2), stat3 = stat3 + VALUES(stat3)
    
    0 讨论(0)
  • 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;

    0 讨论(0)
  • 2020-12-03 18:04

    Add a computed column (sum) and include that in your PK.

    However, this does denormalize your table. You could use a surrogate key and do the calculation in your SELECT

    0 讨论(0)
提交回复
热议问题