MYSQL更新用句子if

时间:2014-11-04 17:50:18

标签: mysql sql-update

需要创建句子更新需要这样的东西:

update table1
set lp=1, mpe=0, pe=0, f2_lp=0, f1_lp=0, mvlp=0 if (lp=1)
set lp=0, mpe=1, pe=0, f2_lp=0, f1_lp=0, mvlp=0 if (mpe=1)
set lp=0, mpe=0, pe=1, f2_lp=0, f1_lp=0, mvlp=0 if (pe=1)
set lp=0, mpe=0, pe=0, f2_lp=1, f1_lp=0, mvlp=0 if (f2_lp=1)
set lp=0, mpe=0, pe=0, f2_lp=0, f1_lp=1, mvlp=0 if (f1_lp=1)
set lp=0, mpe=0, pe=0, f2_lp=0, f1_lp=0, mvlp=1 if (mvpl=1)

2 个答案:

答案 0 :(得分:1)

首先重温一下这个条件。我通常建议你使用case,但也许可以按照你想要的那样做:

update table1
    set lp = (lp = 1),
        mp2 = (mp2 = 1),
        mpe = (mpe = 1),
        f2_lp = (f2_lp = 1),
        f1_lp = (f1_lp = 1),
        mvlp = (mvlp= 1);

这不是完全你想要的。对于你似乎描述的内容:

update table1 
     set lp = (case when lp = 1 then 1 else 0 end),
         mp2 = (case when lp = 1 then 0 when mp2 = 1 then 1 else 0 end),
         mpe = (case when lp = 1 or mp2 = 1 then 0 when mpe = 1 then 1 else 0 end),
         f2_lp = (case when lp = 1 or mp2 = 1 or mpe = 1 then 0 when f2_lp = 1 then 1 else 0 end),
          . . .

答案 1 :(得分:0)

您可能希望将其分成多个更新语句,并在每个更新语句中使用WHERE子句来强制执行您的条件。

由于执行顺序很重要,因此您应该谨慎实施。例如,如果您有一行lp=1mpe=1,您想要做什么?您要设置lp=0还是设置mpe=0

以下是基于您的代码段的示例,以帮助您入门:

update table1
set lp=1, mpe=0, pe=0, f2_lp=0, f1_lp=0, mvlp=0 
where (lp=1)

update table1
set lp=0, mpe=1, pe=0, f2_lp=0, f1_lp=0, mvlp=0 
where (mpe=1)

update table1
set lp=0, mpe=0, pe=1, f2_lp=0, f1_lp=0, mvlp=0 
where (pe=1)

update table1
set lp=0, mpe=0, pe=0, f2_lp=1, f1_lp=0, mvlp=0 
where (f2_lp=1)

update table1
set lp=0, mpe=0, pe=0, f2_lp=0, f1_lp=1, mvlp=0 
where (f1_lp=1)

update table1
set lp=0, mpe=0, pe=0, f2_lp=0, f1_lp=0, mvlp=1 
where (mvpl=1)