How does MySQL CASE work?

前端 未结 3 1372
野性不改
野性不改 2020-11-29 02:03

I know that SQL\'s CASE syntax is as follows:

CASE
    WHEN search_condition THEN statement_list
    [WHEN search_condition THEN statement_list]         


        
3条回答
  •  佛祖请我去吃肉
    2020-11-29 02:50

    CASE in MySQL is both a statement and an expression, where each usage is slightly different.

    As a statement, CASE works much like a switch statement and is useful in stored procedures, as shown in this example from the documentation (linked above):

    DELIMITER |
    
    CREATE PROCEDURE p()
      BEGIN
        DECLARE v INT DEFAULT 1;
    
        CASE v
          WHEN 2 THEN SELECT v;
          WHEN 3 THEN SELECT 0;
          ELSE
            BEGIN -- Do other stuff
            END;
        END CASE;
      END;
      |
    

    However, as an expression it can be used in clauses:

    SELECT *
      FROM employees
      ORDER BY
        CASE title
          WHEN "President" THEN 1
          WHEN "Manager" THEN 2
          ELSE 3
        END, surname
    

    Additionally, both as a statement and as an expression, the first argument can be omitted and each WHEN must take a condition.

    SELECT *
      FROM employees
      ORDER BY
        CASE 
          WHEN title = "President" THEN 1
          WHEN title = "Manager" THEN 2
          ELSE 3
        END, surname
    

    I provided this answer because the other answer fails to mention that CASE can function both as a statement and as an expression. The major difference between them is that the statement form ends with END CASE and the expression form ends with just END.

提交回复
热议问题