How do I use properly CASE..WHEN in MySQL

后端 未结 6 1199
我在风中等你
我在风中等你 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 16:18

    CASE course_enrollment_settings.base_price is wrong here, it should be just CASE

    SELECT 
    CASE 
    WHEN course_enrollment_settings.base_price = 0      THEN 1 
    WHEN course_enrollment_settings.base_price<101      THEN 2 
    WHEN course_enrollment_settings.base_price>100 AND    
                      course_enrollment_settings.base_price<201 THEN 3 
        ELSE 6 
    END AS 'calc_base_price', 
    course_enrollment_settings.base_price 
    FROM 
      course_enrollment_settings 
    WHERE course_enrollment_settings.base_price = 0 
    

    Some explanations. Your original query will be executed as :

    SELECT 
    CASE 0
    WHEN 0=0 THEN 1 -- condition evaluates to 1, then 0 (from CASE 0)compares to 1 - false
    WHEN 0<1 THEN 2 -- condition evaluates to 1,then 0 (from CASE 0)compares to 1 - false
    WHEN 0>100 and 0<201 THEN 3 -- evaluates to 0 ,then 0 (from CASE 0)compares to 0 - true
    ELSE 6, ...
    

    it's why you always get 3

提交回复
热议问题