当我使用重复密钥更新时如何使用验证

时间:2016-06-09 06:29:56

标签: mysql duplicates

当我使用重复密钥更新

INSERT INTO test_table (name, age, date) 
       VALUES (Kevin, 20, now)
       ON DUPLICATE KEY UPDATE name = VALUES(name),
                               age = VALUES(age),
                               date = VALUES(date)

我想与现有的验证值进行比较 我该怎么办?

我尝试了一些方法

where date < VALUES(date)

但所有方法都是语法错误

感谢您阅读

2 个答案:

答案 0 :(得分:1)

尝试使用CASE EXPRESSION

INSERT INTO test_table (name, age, date) 
       VALUES (Kevin, 20, now)
       ON DUPLICATE KEY 
       UPDATE name = CASE WHEN `date`< values(`date`) THEN VALUES(name) ELSE name end,
              age= CASE WHEN `date`< values(`date`) THEN VALUES(age) ELSE age end,
              `date`= CASE WHEN `date`< values(`date`) THEN VALUES(date) ELSE `date` end

答案 1 :(得分:0)

INSERT INTO test_table (name, age, date) 
       VALUES (Kevin, 20, now)
       ON DUPLICATE KEY UPDATE age =  IF(`date` < values(`date`), values(age), age),
                               name = IF(`date` < values(`date`), values(name), name),
                               date = IF(`date` < values(`date`), values(date), date)