是否有任何单个sql语句进行批量更新?

时间:2013-10-17 08:45:16

标签: mysql sql

我只有一个sql怀疑,实际上我需要为每个颜色值多次使用更新查询...每次检查每种颜色的条件变得困难..

在批量'更新'下面是否有任何单个sql语句?请告诉我..

update `myTable` set `COLOR`='white'  WHERE `CATEGORY` = 'Dress' and `NAME` like '%white%'
update `myTable` set `COLOR`='red'  WHERE `CATEGORY` = 'Dress' and `NAME` like '%red%'
update `myTable` set `COLOR`='blue'  WHERE `CATEGORY` = 'Dress' and `NAME` like '%blue%'
update `myTable` set `COLOR`='pink'  WHERE `CATEGORY` = 'Dress' and `NAME` like '%pink%'

2 个答案:

答案 0 :(得分:0)

update `myTable` set `COLOR`=CASE WHEN NAME LIKE '%white%' THEN 'white'  
WHEN NAME LIKE '%red%' THEN 'red'
...
END /*ends the CASE statement*/
WHERE `CATEGORY` = 'Dress' and 
(
`NAME` like '%white%' OR
`NAME` like '%red%' OR
...
)

实际上,由于LIKE '%whatever'的查询无论如何都必须进行全表扫描,您可以这样做:

update `myTable` set `COLOR`=CASE WHEN NAME LIKE '%white%' THEN 'white'  
WHEN NAME LIKE '%red%' THEN 'red'
...
ELSE `COLOR`
END /*ends the CASE statement*/
WHERE `CATEGORY` = 'Dress' 

编写起来比较容易,但你也会更新每一行(如果MySQL不够聪明,那么有时会更新之前的值)。

答案 1 :(得分:0)

您可以使用CASE

Update  myTable
SET     COLOR = CASE 
                     WHEN  CATEGORY = 'white' AND NAME like '%white%' THEN 'white'
                     WHEN  CATEGORY = 'red' AND NAME like '%red%' THEN 'red'
                     WHEN  CATEGORY = 'blue' AND NAME like '%blue%' THEN 'blue'
                     WHEN  CATEGORY = 'pink' AND NAME like '%pink%' THEN 'pink'
                     ELSE  value 
                END
WHERE   CATEGORY  IN ('white','red','blue','pink')