MySQL CASE…WHERE…THEN statements

后端 未结 2 1410
伪装坚强ぢ
伪装坚强ぢ 2020-12-09 12:03

I have a MySQL UPDATE statement that uses a CASE clause

UPDATE partsList SET quantity =  
CASE
  WHEN partFK = 1 THEN 4
  WHEN partFK = 2 THEN 8
END
WHERE bu         


        
相关标签:
2条回答
  • 2020-12-09 12:16

    It isn't that the CASE must have more than one, WHEN...THEN, it's that it must handle all the data you give it.

    If you removed one of the clauses, you leave a hole. e.g.

    UPDATE partsList SET quantity =  
    CASE
      WHEN partFK = 1 THEN 4
    END
    WHERE buildFK = 1;
    

    With this update statement, if parkFK is 2, then the update fails because the CASE can't handle the input.

    You can either limit your source data by adding another line to your where-clause (e.g. AND partFK in (1,2)), or you could add an ELSE to the case expression.

    UPDATE partsList SET quantity =  
    CASE
      WHEN partFK = 1 THEN 4
      WHEN partFK = 2 THEN 8
      ELSE 12 
    END
    WHERE buildFK = 1;
    

    However, based on the SQL statement you've shown, there is probably a better way. Presumably, partFK is a foreign-key to some other table. Can you pull the value for quantity from there?

    0 讨论(0)
  • 2020-12-09 12:23

    Add ELSE NULL or something before the END of the case. See http://dev.mysql.com/doc/refman/5.0/en/case-statement.html for more info.

    0 讨论(0)
提交回复
热议问题