2013-10-17 42 views
0

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

回答

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') 
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不夠聰明,不能更新)。