插入到……重复密钥更新……。有条件?

INSERT INTO … ON DUPLICATE KEY UPDATE …. with condition?

我仍然想知道 MySQL 5.7

中是否有类似条件重复更新的东西

我有一个 table 由不同的来源更新。

假设我有一个 table

CREATE TABLE t 
(
    name VARCHAR(100),
    value INT,
    last update DATETIME
)

我有 3 行

name value lastupdate
a 10 2021-01-01
b 20 2021-02-01
c 30 2021-03-01

现在我有一些数据要导入

name value lastupdate
a 20 2021-01-01
b 40 2021-01-01
c 60 2021-04-01

查询结果应该是

name value lastupdate
a 20 2021-01-01
b 20 2021-02-01
c 60 2021-03-01

这可以通过一个插入查询来完成,还是我必须先检查 table 中现有数据的最后更新是否比导入数据的日期更新?

假设name是table的PRIMARY KEY或者定义为UNIQUE,你可以使用CASE表达式:

INSERT INTO t (name, value, lastupdate) VALUES
  ('a', 20, '2021-01-01'),
  ('b', 40, '2021-01-01'),
  ('c', 60, '2021-04-01')
ON DUPLICATE KEY UPDATE
value = CASE WHEN VALUES(lastupdate) >= lastupdate THEN VALUES(value) ELSE value END;

参见demo

注意(来自INSERT ... ON DUPLICATE KEY UPDATE Statement):

The use of VALUES() to refer to the new row and columns is deprecated beginning with MySQL 8.0.20, and is subject to removal in a future version of MySQL. Instead, use row and column aliases, as described in the next few paragraphs of this section.

因此,如果您的 MySql 版本是 8.0.20+,建议使用别名而不是 VALUES():

INSERT INTO t (name, value, lastupdate) VALUES
  ('a', 20, '2021-01-01'),
  ('b', 40, '2021-01-01'),
  ('c', 60, '2021-04-01') AS new
ON DUPLICATE KEY UPDATE
t.value = CASE WHEN new.lastupdate >= t.lastupdate THEN new.value ELSE t.value END;

参见demo