2016-06-09 65 views
1

如何使用驗證當我使用重複鍵更新當我使用重複鍵更新

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) 

但是所有的方法都是語法錯誤

感謝您閱讀

回答

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 
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)