简体   繁体   English

mysql具有多个条件的情况

[英]case when mysql with multiple conditions

I made the following case when statement in my sql: 我在sql中声明了以下情况:

SELECT 
*,
CASE
    WHEN lead_time < 14 THEN 0
    WHEN (14 <= lead_time < 21 AND days_passed = 8) THEN 1
    WHEN
        (21 <= lead_time < 28
            AND days_passed = 15)
    THEN
        1
    WHEN
        (28 <= lead_time < 42
            AND days_passed = 22)
    THEN
        1
    WHEN
        (42 <= lead_time < 56
            AND days_passed = 36)
    THEN
        1
    WHEN
        (56 <= lead_time < 84
            AND days_passed = 29)
    THEN
        1
    WHEN
        (56 <= lead_time < 84
            AND days_passed = 50)
    THEN
        1
    WHEN (lead_time > 84 AND days_passed = 36) THEN 1
    WHEN (lead_time > 84 AND days_passed = 57) THEN 1
    ELSE 0
END AS send_email

I do not get any error. 我没有任何错误。 However, when I check the results I get: 但是,当我检查结果时,我得到:

# lead_time, days_passed, send_email
99, 15, 1
99, 22, 1
99, 15, 1
99, 8, 1
99, 8, 1
99, 8, 1
99, 8, 1
85, 29, 1
57, 50, 1
18, 36, 1
99, 22, 1
99, 22, 1
99, 22, 1
99, 22, 1
99, 22, 1
15, 15, 1
15, 15, 1
99, 8, 1
99, 8, 1
99, 8, 1
99, 8, 1

It seems as if the 'and' in the query behaves as an 'or'. 似乎查询中的“和”表现为“或”。 Any idea why?. 知道为什么吗? Thanks, 谢谢,

MySQL doesn't support a syntax: MySQL不支持语法:

min <= expr <= max

Such kinds of expressions can be written as: 这类表达可以写成:

WHERE expr >= min AND expr <= max

or with using operator BETWEEN (please note that BETWEEN is inclusive): 或使用运算符BETWEEN(请注意BETWEEN包含在内):

WHERE expr BETWEEN min AND max

Comparison operators in MySQL: http://dev.mysql.com/doc/refman/5.5/en/comparison-operators.html MySQL中的比较运算符: http : //dev.mysql.com/doc/refman/5.5/en/comparison-operators.html

The comparison 14 <= lead_time < 21 AND days_passed = 8 is checked in sequence, so in a way you have: 按顺序检查比较14 <= lead_time < 21 AND days_passed = 8 ,因此您可以:

((14 <= lead_time) < 21) AND (days_passed = 8)

Which is always true because 14 <= lead_time equals 1 and thus your comparison is equal to: 这总是true因为14 <= lead_time等于1,因此您的比较等于:

( 1 < 21 ) AND days_passed = 8

You should use a between or an and for each comparison. 您应该为每个比较使用betweenbetween and between

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM