Mysql 插入多行,如果重复值列则更新

Mysql insert multiple rows, if duplicate value column then update

我有一个 MySQL table 看起来像这样

id | customer_id | textkey | value |
---+-------------+---------+-------+
 1 |           1 | text1   | value1|
 2 |           1 | text2   | value2|
 3 |           1 | text3   | value3|
 4 |           1 | text4   | value4|
 5 |           2 | text1   | value1|
...

我想将以下值插入 customer_id 1

(text1, valueX), (text3, valueY), (text5, value5), (text6, value6)

最终结果应该是这样的

mysql> SELECT * from MyTable where customer_id=1;

id | customer_id | textkey | value |
---+-------------+---------+-------+
 1 |           1 | text1   | valueX|
 2 |           1 | text2   | value2|
 3 |           1 | text3   | valueY|
 4 |           1 | text4   | value4|
 6 |           1 | text5   | value5|
 7 |           1 | text6   | value6|

只要 textkey 插入中有重复项,value 列就应该更新,如果 textkey 不是重复项,则定期插入。我可以使用什么查询来实现这一目标?我尝试使用 IGNORE、LAST_INSERT_ID() 和 ON DUPLICATE KEY UPDATE,但我无法弄清楚什么适用于“ON DUPLICATE COLUMN UPDATE”场景。谢谢

您必须创建唯一索引以检测重复:

CREATE UNIQUE INDEX idx ON test (customer_id, textkey);

现在您可以使用 INSERT .. ODKU:

INSERT INTO test (customer_id, textkey, value) VALUES
(1, 'text1', 'valueX'), 
(1, 'text3', 'valueY'), 
(1, 'text5', 'value5'), 
(1, 'text6', 'value6')
ON DUPLICATE KEY UPDATE
value = VALUES(value);

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=6dcc351706f574f4c9f13c1fc95b9225