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_settings.base_price
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
base_price
is decimal(8,0)
When run this on my DB, I get:
3 0
3 0
3 0
3 0
3 0
Remove the
course_enrollment_settings.base_price
immediately afterCASE
:CASE
has two different forms, as detailed in the manual. Here, you want the second form since you're using search conditions.There are two variants of
CASE
, and you're not using the one that you think you are.What you're doing
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:Now,
(case_value > 100)
evaluates toFALSE
, and is the only one of your conditions to do so. So, now you have:FALSE
converts to0
and, through the resulting full expressionif (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 nocase_value
, causing MySQL to know that you intend to use the second variant ofCASE
:Now you can provide your full conditionals as
search_condition
.Also, please read the documentation for features that you use.
Or:
here CASE is an expression in 2nd scenario search_condition will evaluate and if no search_condition is equal then execute else
should be
CASE course_enrollment_settings.base_price
is wrong here, it should be justCASE
Some explanations. Your original query will be executed as :
it's why you always get 3
I think part of it is that you're stating the value you're selecting after
CASE
, and then usingWHEN x = y
syntax afterward, which is a combination of two different methods of usingCASE
. It should either beor