1. 程式人生 > >mysql case when update

mysql case when update

需求是根據某個欄位的值不同,修改相對應的另一個欄位,於是就用到了mysql的case when,在此記錄一下。隱私起見隨便修改了表名和欄位名。

有種簡單的情況是隻需要判斷某個欄位的值就可以確定另一個欄位的值:

UPDATE mytalbe SET 
propertyA = CASE id 
        WHEN 1 THEN 3 
        WHEN 2 THEN 4 
        WHEN 3 THEN 5 
END, 
propertyB = CASE id 
        WHEN 1 THEN 'aaa'
        WHEN 2 THEN 'bbb'
        WHEN
3 THEN 'ccc' END WHERE id IN (1,2,3);

另一種情況是要判斷某個欄位是否滿足某個表示式,來做相應修改,我今天遇到的情況就是這樣。如下:

UPDATE mytable 
SET propertyA = 
CASE 
    WHEN left(number, 1)='1' THEN 1 -- number這個varchar型別的欄位開頭為“1”,則設定propertyA為1
    WHEN left(number, 1)='2' THEN 2 -- number這個varchar型別的欄位開頭為“2”,則設定propertyA為2
    WHEN left
(number, 1)='3' THEN 3 WHEN left(number, 1)='4' THEN 4 WHEN left(number, 1)='5' THEN 5 WHEN left(number, 1)='5' THEN 6 ELSE 0 END, propertyB = CASE WHEN CARGO_TAX_RATE in (0.17,0.13,0.11,0.06) THEN 1 -- 17%或13%或11%或6%,1 WHEN CARGO_TAX_RATE in (0.05,0.04,0.03) THEN 2 -- 5%或4%或3
%,2 ELSE 4 -- 0% 或者其他,預設免稅 END, propertyC = 1, -- propertyC這個屬性預設為1 propertyD = 0 -- propertyD這個屬性預設為0 WHERE EID IN (277) AND NATURE_OF_THE_INVOICE_LINE_NEW IN (0, 4, 8) AND BILLING_DATE >= "2017-03-01" AND BILLING_DATE <= "2018-03-05" AND IS_DELETE = 0