MYSQL批量按条件更新不一样的数据

首先,咱们须要了解下MYSQL CASE EXPRESSION 语法。
php

手册传送门:http://dev.mysql.com/doc/refman/5.7/en/control-flow-functions.htmlhtml

有关这个的讨论的stackoverflow:http://stackoverflow.com/questions/29205842/can-mysql-case-expression-running-well-with-the-same-when-conditionmysql


看完以上,你就会少走不少弯路。sql

我有不少条记录须要更新不一样的值怎么办呢?express

咱们能够这样:
app

UPDATE activity
SET number = CASE
WHEN aid = 45 THEN
    number + 1 
WHEN aid = 43 THEN
    number + 1 
END
WHERE
    aid IN (45, 43)

或者这样:code

UPDATE activity
SET number = CASE aid 
WHEN 45 THEN
    number + 1 
WHEN 43 THEN
    number + 1 
END
WHERE
    aid IN (45, 43)

这个语法和程序语言中的switch case控制流差很少意思,可是有几点须要注意:htm

ex1:element

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
WHEN aid = 45 THEN
    number + 1
END
WHERE
    aid IN (45, 43,49)

看到了吗?会不会有人一开始像我同样认为aid=45 的number+5的?放心....aid=45 的number就仅仅加了1.换句话说也就是第一个when aid=45 then number+1执行了!第二次再碰到when aid=45的时候,系统就认为这个条件已经执行过了,后门的aid=45就直接跳过不执行的了,可是中间的aid=43 aid=49的仍是能够正常执行的!get

也就是说,全部相同的when条件就只执行第一次!


ex2:

UPDATE activity
SET number = CASE aid 
WHEN 45 THEN
    number + 1 
WHEN 43 THEN
    number + 1 
END

这个你以为会怎么样?貌似和上面的没啥不一样啊?这个就糟糕了.....若是没有约束条件,那么aid=45 aid=43的number+1之外,别的aid都会set number=null.....这就好像你用简单版的update set没有写where条件来约束范围的状况同样。当心当心.....


这里只讨论了如何使用CASE EXPRESSION 来进行批量更新.....

不管是insert 或者update,批量处理老是要比一个个来的要效率,固然这里指的是通常状况下的使用。最后来看看在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);

注意语句连接要适当给予空格....

相关文章
相关标签/搜索