如你所见:
UPDATE activity
SET number = CASE
WHEN aid = 45 THEN
number + 1
WHEN aid = 43 THEN
number + 1
END
WHERE
aid IN (45, 43)
此查询运行良好。 但是:
UPDATE activity
SET number = CASE
WHEN aid = 45 THEN
number + 1
WHEN aid = 43 THEN
number + 1
WHEN aid = 45 THEN
number + 3
WHEN aid = 49 THEN
number + 1
END
WHERE
aid IN (45, 43,49)
查询有问题。第二个" WHEN援助= 45 ..."结果是当援助= 45时,数字增加1,但我希望数字增加4。
感谢您的回答。但我认为我的问题描述得如此简单。所以,我可能应该详细描述一下。 有我的PHP代码可以更新不同活动的号码。援助是主键。
/*
$aids is an array which the key is the activity's primary key and the
value is the activity's number.
example $aids = array('45'=>4,'43'=>1...)
In the array,i combine all the same aid to one element.so one aid can
not be used twice by the case expression.And all the number are total
number.
*/
$sql = 'update huodong_activity set applynumber = case ';
$aids_str = implode(',',array_keys($aids));
foreach($aids as $k=>$v){
$sql .= sprintf(' when aid = %d then applynumber-%d',$k,$v);
}
$sql .= ' END WHERE aid IN ('.$aids_str.') ';
$db->query($sql);
我的问题是:
1.我真的不知道为什么案例表达不能通过" aid = 45"使用了两次或更多?
2.我不知道"更新案例表达式可以更新多少行"或任何限制?
答案 0 :(得分:1)
第二个版本不起作用,因为case表达式将匹配前45个然后停止。只需删除WHEN aid = 45 THEN number + 1
,然后将第二个更改为WHEN aid = 45 THEN number + 4
,如果您想将其增加4,请执行以下操作:
UPDATE activity
SET number = CASE
WHEN aid IN (43, 49) THEN
number + 1
WHEN aid = 45 THEN
number + 4
END
WHERE
aid IN (45, 43, 49)