How to use If Then Else in a MySQL update query?

前端 未结 2 919
太阳男子
太阳男子 2021-02-09 12:37

I want to update a table in MySQL like this:

UPDATE Table
SET A = \'20\' IF A > 20
SET A = A    IF A < 20 
SET A = 0    IF A <= 1
WHERE A IS NOT NULL;
<         


        
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-09 13:31

    UPDATE Table
    SET A = Case
    When A > 20 Then 20 
    When A <= 1 Then 0
    End
    WHERE A IS NOT NULL and ( A > 20 or A <= 1 )
    

    or more simply, 2 statements

    UPDATE Table
    SET A = 20 
    where A > 20;
    
    UPDATE Table
    SET A = 0
    where A <= 1;
    

提交回复
热议问题