INSERT ... ON DUPLICATE KEY UPDATE [IF]

时间:2014-06-02 18:08:05

标签: mysql on-duplicate-key

这个查询显然不会起作用,因为它是MySQL和PHP的混合体,它只是用可读性的术语来解释我的目标:

INSERT INTO table 
    (userid, courseid, valid_days, valid_to) 
VALUES 
    ('1', '1', '28', '1401732028') 
ON DUPLICATE KEY UPDATE 
    (If the existing records valid_to == 0 || NULL){ 
         //then add the value of valid_days to the existing records valid_days field
    }else{
         //then turn the submitted valid_days (28) into seconds and add it to the existing valid_to value
    }

我希望这是有道理的,并且抱歉以可怕的方式使用PHP和MySQL来解释问题:)

谢谢!

1 个答案:

答案 0 :(得分:3)

您可以在if()的逻辑中使用caseon duplicate key update。我可能不明白这样做的目的,但我认为以下实现它:

INSERT INTO table (userid, courseid, valid_days, valid_to) 
    VALUES ('1', '1', '28', '1401732028') 
    ON DUPLICATE KEY UPDATE 
        valid_days = (case when valid_to = 0 or valid_to is null
                           then valid_days + values(valid_days)
                           else valid_days
                      end),
        valid_to = (case when valid_to > 0
                         then valid_to + values(valid_days)*60*60*24
                         else valid_to
                    end);