如何在 MySQL 中正确使用 CASE..WHEN

2021-11-20 00:00:00 sql conditional switch-statement mysql case

这是一个演示查询,注意它很简单,只在 base_price 为 0 的地方获取,并且仍然选择条件 3:

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_pricedecimal(8,0)

在我的数据库上运行时,我得到:

When run this on my DB, I get:

3 0
3 0
3 0
3 0
3 0

3 0
3 0
3 0
3 0
3 0

推荐答案

CASE之后立即删除course_enrollment_settings.base_price:

SELECT
   CASE
    WHEN course_enrollment_settings.base_price = 0      THEN 1
    ...
    END

CASE 有两种不同的形式,详见手册.在这里,您需要第二种形式,因为您使用的是搜索条件.

CASE has two different forms, as detailed in the manual. Here, you want the second form since you're using search conditions.

相关文章