How do I use properly CASE..WHEN in MySQL

后端 未结 6 1202
我在风中等你
我在风中等你 2020-12-01 15:53

Here is a demo query, notice it is very simple, Fetches only where base_price is 0, And still, it chooses the condition 3:

SELECT
   CASE course_enrollment_s         


        
6条回答
  •  没有蜡笔的小新
    2020-12-01 15:57

    There are two variants of CASE, and you're not using the one that you think you are.

    What you're doing

    CASE case_value
        WHEN when_value THEN statement_list
        [WHEN when_value THEN statement_list] ...
        [ELSE statement_list]
    END CASE
    

    Each condition is loosely equivalent to a if (case_value == when_value) (pseudo-code).

    However, you've put an entire condition as when_value, leading to something like:

    if (case_value == (case_value > 100))
    

    Now, (case_value > 100) evaluates to FALSE, and is the only one of your conditions to do so. So, now you have:

    if (case_value == FALSE)
    

    FALSE converts to 0 and, through the resulting full expression if (case_value == 0) you can now see why the third condition fires.

    What you're supposed to do

    Drop the first course_enrollment_settings so that there's no case_value, causing MySQL to know that you intend to use the second variant of CASE:

    CASE
        WHEN search_condition THEN statement_list
        [WHEN search_condition THEN statement_list] ...
        [ELSE statement_list]
    END CASE
    

    Now you can provide your full conditionals as search_condition.

    Also, please read the documentation for features that you use.

提交回复
热议问题