mysql多个值()包括,需要根据条件进行更新

时间:2018-07-23 09:23:25

标签: mysql sql

如果一列的值等于soemthing,我需要更新重复键上的字段。现在我有这样的东西:

INSERT INTO `table` (metric,amount,something1,something2)
VALUES              (metric,amount,something1,something2),
                    (metric,amount,something1,something2),
                    (metric,amount,something1,something2)
ON DUPLICATE KEY UPDATE 
amount = IF (metric = '6', amount = amount + ( '"+amount+"'),'')
         ELSEIF (metric = '8' ,     amount = amount + ( '"+impressions+"') ,'')  
         ELSEIF (metrtic = '11' ,   amount = amount + ( '"+impressions+"') ,'');

我在这里做什么错了?

2 个答案:

答案 0 :(得分:1)

如果我理解正确,则可以将UPDATEJOIN一起使用自己的CASE WHEN

[DUPLICATE KEY]可以填写您要检查的DUPLICATE列。

UPDATE `table` r
JOIN (
    SELECT Count(*) cnt,[DUPLICATE KEY] 
    from `table`
    group by [DUPLICATE KEY]
) t1 on r.[DUPLICATE KEY] = t1.[DUPLICATE KEY] and t1.cnt > 1
SET r.amount = (CASE WHEN r.metric = '6' THEN r.amount+ ( '"+amount+"'),'' 
                  WHEN r.metric = '8' THEN r.amount + ( '"+impressions+"') ,''
                  WHEN r.metric = '11' THEN r.amount+ ( '"+impressions+"') ,''
                  ELSE r.amount
            END)

答案 1 :(得分:0)

最终对我有用的是:

INSERT INTO `table` (metric,amount,something1,something2)
VALUES              (metric,amount,something1,something2),
                    (metric,amount,something1,something2),
                    (metric,amount,something1,something2)
ON DUPLICATE KEY UPDATE 
                metric = VALUES(metric),
                amount = amount + VALUES (amount),
                modified = NOW(),
                something1= VALUES(something1);

希望这对以后的所有人都有帮助。