2016-02-23 70 views
0
Name id Col1 Col2 Col3 
Row1 1 6  1  A  
Row2 2 2  3  B  
Row3 3 9  5  B  
Row4 4 16 8  C  

多行我想更新与状态栏。SQL更新条件

在第一行,

update col2 = Col1+0 if Col3 = A 
OR 
col2 = Col1-0 if Col3 = B 
OR 
col2 = Col1*0 if Col3 = C 

在第二排,

update col2 = (previous col2) + Col1 if Col3 = A 
OR 
col2 = (previous col2) - Col1 if Col3 = B 
OR 
col2 = (previous col2) * Col1 if Col3 = C 

同样进入第三排

+0

MySQL的..感谢回复 –

回答

1

我认为你可以做你想做的一个case语句和变量:

set @prev_col2 = 0; 

update t 
    set col2 = (case when (@col2 := @prev_col2) = NULL then -1 -- never happens 
        when (@prev_col2 := col2) = NULL then -1 -- never happens 
        when col3 = 'A' then Col1 + @col2 
        when col3 = 'B' then Col1 - @col2 
        when Col3 = 'C' then col1 * @col2 
       end) 
    order by id; 
+0

为什么重复?当(@ COL2:= @ prev_col2)= NULL然后-1 - 从未发生 时(@ prev_col2:= COL2)= NULL然后-1 - 从未发生 –

+0

@LimNeo。 。 。因为变量需要分配适当的值。 –

+0

MySQL表示:文件 #1064 - 你在你的SQL语法错误;检查对应于你的MySQL服务器版本使用附近的正确语法手册“=(情况下(@ COL2:= @ prev_col2)= NULL,则-1 时(@prev”第2行 –