MySQL 插入新记录时将旧值增加新值 "on duplicate key update"

MySQL increase the old value by the new value when inserting new records by "on duplicate key update"

我创建了一个新的 table 像这样:

+------------+--------------+------+-----+---------+-------+
| Field      | Type         | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| first      | varchar(100) | NO   | PRI | NULL    |       |
| last       | varchar(400) | NO   | PRI | NULL    |       |
| source     | varchar(100) | NO   |     | NULL    |       |
| count      | int          | YES  |     | 1       |       |
+------------+--------------+------+-----+---------+-------+

然后我尝试使用以下方法向 table 插入多条记录:

insert into my_table(first,last,source,count) values ('a','b','c',50),('a','b','c',20),('d','e','f',30) on duplicate key update count = count + 1;

插入后,这是table的内容:

+------------+-----------+--------+-------+
| first      | last      | source | count |
+------------+-----------+--------+-------+
| a          | b         | c      |     2 |
| d          | e         | f      |     1 |
+------------+-----------+--------+-------+

但是,我希望根据新记录值中提供的数字更新计数(即,在提供的示例中为 50、20 和 30)。所以,table 应该是这样的:

+------------+-----------+--------+-------+
| first      | last      | source | count |
+------------+-----------+--------+-------+
| a          | b         | c      |    70 |
| d          | e         | f      |    30 |
+------------+-----------+--------+-------+

是否可以使用 MySQL 中的“重复密钥更新”来实现此目的?或者有没有其他有效的方法来实现这一目标? table 将非常大(有数百万行)。

考虑 VALUES() 语法,您可以在 on duplicate key 子句中使用它来引用本应插入的列值:

insert into my_table(first, last, source, count) 
values ('a','b','c',50), ('a','b','c',20), ('d','e','f',30) 
on duplicate key update count = count + VALUES(count);

注:firstlastsourceMySQL keywords。我不建议将它们用作列名。

VALUES() 是使用的方法,如 GMB 所述,如果您使用的 mysql 版本早于 8.0.19。但是,从 8.0.20 开始,它已被弃用,如果您使用 mysql 8.0.19 或更新版本,建议为要插入的行指定一个别名,然后通过别名引用插入的值,例如这个:

insert into my_table (first, last, source, count) 
values ('a','b','c',50), ('a','b','c',20), ('d','e','f',30) as newRow
on duplicate key update count = count + newRow.count;

可在此处找到更多信息:https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html