这是我的查询?
UPDATE users
SET reputation = reputation - (CASE WHEN id = 29 THEN 2
WHEN id = 30 AND NOT 0 THEN 15
ELSE 0
END)
WHERE id IN (30, 29);
有时会抛出此错误:
#1690 - BIGINT UNSIGNED值超出范围'(spy.users.reputation - (情况下(spy.users.id = 29)然后2时((spy.users.id = 30)和(不是(0)))然后15其他0结束))'
正如您在错误消息中看到的那样,reputation
列是 UNSIGNED ,我需要至少保留1
..与stackoverflow完全相同:如果是用户有一个代表,他得到一个downvote,他的代表将仍然是1
。那么如何修复该更新查询以防止在这种情况下失败?
答案 0 :(得分:1)
使用greatest()
:
UPDATE users
SET reputation = GREATEST(reputation -
(CASE WHEN id = 29 THEN 2
WHEN id = 30 AND NOT 0 THEN 15
ELSE 0
END),
1)
WHERE id IN (30, 29);
编辑:
试试这个版本:
UPDATE users
SET reputation = (CASE WHEN reputation > (CASE WHEN id = 29 THEN 2
WHEN id = 30 THEN 15
ELSE 0
END)
THEN reputation - (CASE WHEN id = 29 THEN 2
WHEN id = 30 THEN 15
ELSE 0
END)
ELSE 1
END)
WHERE id IN (30, 29);
问题是中间计算。我认为MySQL可以正确地进行中间计算,然后在赋值时失败。