0

我只是有一个 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%'
4

2 回答 2

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 不够聪明,无法更新)。

于 2013-10-17T08:48:58.150 回答
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')  
于 2013-10-17T08:53:01.630 回答