当mysql具有多个条件时的情况

时间:2016-02-29 11:46:20

标签: mysql case

我在我的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

我没有收到任何错误。但是,当我检查结果时,我得到了:

# 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

似乎&#39;和&#39;在查询中表现为&#39;或&#39;。知道为什么吗? 谢谢,

2 个答案:

答案 0 :(得分:3)

MySQL不支持语法:

min <= expr <= max

这类表达式可以写成:

WHERE expr >= min AND expr <= max

或使用运算符BETWEEN(请注意BETWEEN是包含的):

WHERE expr BETWEEN min AND max

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

答案 1 :(得分:2)

按顺序检查比较14 <= lead_time < 21 AND days_passed = 8,因此您可以使用以下方式:

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

始终为true,因为14 <= lead_time等于1,因此您的比较等于:

( 1 < 21 ) AND days_passed = 8

每次比较都应使用betweenand