使用if语句更新表

时间:2012-12-12 11:49:11

标签: mysql

我正在尝试使用此命令使用IF语句更新saving.balance

UPDATE TABLE saving s, time t
SET s.balance = IF(t.currency_TYPE = ‘RMB’, s.balance + t.balance * t.interest)
WHERE t.ID = 'input'
AND s.User = t.User;

然而,MySQL给了我ERROR 1064,有什么问题以及如何纠正它?

3 个答案:

答案 0 :(得分:2)

你忘了IF函数和其他语法中的第3个参数: - )

为什么你让脚本不在哪里?像这样:

UPDATE saving s
INNER JOIN time t
    ON t.ID = 'input'
    AND t.User = s.User
SET s.balance = s.balance + t.balance * t.interest
WHERE t.currency_TYPE = 'RMB';

您将使用currency_type rmb更新记录!

OR

UPDATE saving s
INNER JOIN time t
    ON t.ID = 'input'
    AND t.User = s.User
SET s.balance = (t.currency_TYPE = 'RMB', s.balance + t.balance * t.interest, 0);

答案 1 :(得分:2)

请改为尝试:

UPDATE saving s
INNER JOIN `time` t ON s.`User` = t.`User`
SET s.balance = CASE 
                  WHEN t.currency_TYPE = 'RMB' THEN s.balance + 
                                                    t.balance * t.interest
                  ELSE s.balance -- Don't forgot this, default is NULL
                END
WHERE t.ID = 'input';

UPDATE saving s
INNER JOIN `time` t ON s.`User` = t.`User`
SET s.balance = s.balance + t.balance * t.interest
WHERE t.ID = 'input'
  AND t.currency_TYPE = 'RMB' ;

答案 2 :(得分:1)

您需要提及其他部分

UPDATE TABLE saving s, time t
SET s.balance = IF(t.currency_TYPE = ‘RMB’, s.balance + t.balance * t.interest , 0)
WHERE t.ID = 'input'
AND s.User = t.User;