MYSQL根据特定规则填充日期字段

时间:2014-06-06 22:56:48

标签: mysql

我想知道我是否可以在mysql中获得一些查询帮助。以下是我到目前为止所提出的:

CASE
WHEN Field1 = ''
     OR Field1 IS NULL
     AND Field2 <> ''
     OR Field2 IS NOT NULL
     AND Field3 = 'Monthly'
     AND Field4 >= DATE_ADD(curdate(), INTERVAL -1 MONTH)
     OR Field3 = 'quarterly'
     AND Field4 >= DATE_ADD(curdate(), INTERVAL -3 MONTH)
     OR Field3 = 'semi'
     AND Field4 >= DATE_ADD(curdate(), INTERVAL -6 MONTH)
     OR Field3 = 'yearly'
     AND Field4 >= DATE_ADD(curdate(), INTERVAL -12 MONTH) THEN Field4
ELSE ''
END AS Field4,

基本上我要做的是当field1为空但field2不为空时开始下一步:

当field3为Monthly时,field4与当前日期相同或更大但不少于1个月前 或当field3为季度且field4与当前日期相同或更大但不少于3个月前 或当field3为semi且field4与当前日期相同或大于但不小于6个月前 或当field3为Annually且field4与当前日期相同或大于但不低于12个月之前

然后填充field4,否则将其设为空白

非常感谢任何帮助,提前致谢!

1 个答案:

答案 0 :(得分:0)

你忘记了括号。

AND优先于SQL中的OR,因此如果您将条件写为WHERE a OR b AND c,则表示WHERE a OR (b AND c)不是WHERE (a OR b) AND c

在Field2条件之间也不应该OR,但是AND

您的查询应如下所示:

CASE
WHEN (Field1 = '' OR Field1 IS NULL)
    AND Field2 <> ''
    AND Field2 IS NOT NULL
    AND (
         (Field3 = 'Monthly'
             AND Field4 >= DATE_SUB(NOW(), INTERVAL 1 MONTH))
         OR (Field3 = 'quarterly'
             AND Field4 >= DATE_SUB(NOW(), INTERVAL 3 MONTH))
         OR (Field3 = 'semi'
             AND Field4 >= DATE_SUB(NOW(), INTERVAL 6 MONTH))
         OR (Field3 = 'yearly'
             AND Field4 >= DATE_SUB(NOW(), INTERVAL 12 MONTH))
    )
THEN Field4
ELSE ''
END AS Field4,

您也可以尝试这种较短的语法,但我不确定这是否有效。我目前没有可用的MySQL来测试它。

CASE
WHEN (Field1 = '' OR Field1 IS NULL)
    AND Field2 <> ''
    AND Field2 IS NOT NULL
    AND Field4 >= DATE_SUB(NOW(),
        INTERVAL
            (CASE Field3
                WHEN 'Monthly'   THEN 1
                WHEN 'quarterly' THEN 3
                WHEN 'semi'      THEN 6
                WHEN 'yearly'    THEN 12
            END)
        MONTH)
THEN Field4
ELSE ''
END AS Field4,