假设数据是('609933531757547520', 'a', null, 'c')
INSERT INTO tt(id, col_a, col_b, col_c)
VALUES
('609933531757547520', 'a', null, 'c')
ON DUPLICATE KEY UPDATE
col_a=COALESCE('a', col_a)
col_b=COALESCE(null, col_b)
col_c=COALESCE('c', col_c);
COALESCE
返回列表中第一个非 null 项。
EDIT: MySQL 8.0.19 以上可以这么写:
INSERT INTO tt(id, col_a, col_b, col_c)
VALUES
('609933531757547520', 'a', null, 'c') AS new
ON DUPLICATE KEY UPDATE
col_a=COALESCE(new.col_a, col_a)
col_b=COALESCE(new.col_b, col_b)
col_c=COALESCE(new.col_c, col_c);
或者也可以:
INSERT INTO tt(id, col_a, col_b, col_c)
VALUES
('609933531757547520', 'a', null, 'c')
ON DUPLICATE KEY UPDATE
col_a=COALESCE(VALUES(col_a), col_a)
col_b=COALESCE(VALUES(col_b), col_b)
col_c=COALESCE(VALUES(col_c), col_c);
在 ON DUPLICATE KEY UDPATE 中,VALUES()
指向假设未发生冲突时,会被插入的数据。