日期范围麻烦

时间:2014-07-14 14:20:46

标签: mysql

我需要检查在过去“x”天(例如30天)中创建的条目,并且无法使查询生效。这就是我正在使用的:

  SELECT   CAL_OWNER,
           CAL_TITLE,
           FROM_UNIXTIME (CAL_CREATED, "%m-%d-%y") AS CREATED,
           FROM_UNIXTIME (RANGE_START, "%Y-%m-%d") AS DATE2BESEEN,
           CASE CAL_REFERRAL_TYPE
              WHEN 1 THEN 'NoReferral'
              WHEN 2 THEN 'CareyGuide'
              WHEN 3 THEN 'Education'
              WHEN 4 THEN 'Employment'
              WHEN 5 THEN 'Housing'
              WHEN 6 THEN 'Medical'
              ELSE 'NA'
           END
              AS REFERRALS
    FROM   EGW_CAL
   WHERE   CAL_CREATED BETWEEN (NOW () - '30 day') AND NOW ()
ORDER BY   REFERRALS ASC;

如果我注释掉“WHERE range_start ...”行,则查询运行正常,但会提取所有数据 但是,如果我运行完整的查询,它不会出错,但是没有结果(我在过去3周内在列cal_created中有4个条目)。

如果有人可以提供帮助我真的很感激

3 个答案:

答案 0 :(得分:1)

尝试使用INTERVAL和NOW()或CURDATE()..

WHERE FROM_UNIXTIME (CAL_CREATED,'%Y-%m-%d') BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE()

curdate只是当天的日期部分

如果你想包括时间使用NOW()

WHERE FROM_UNIXTIME (CAL_CREATED,'%Y-%m-%d') BETWEEN NOW() - INTERVAL 30 DAY AND NOW()

您还可以使用

之间的新日期
WHERE FROM_UNIXTIME (CAL_CREATED,'%Y-%m-%d') BETWEEN DATE_SUB(NOW(), INTERVAL 30 DAY) AND NOW()

消息来源:http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html

注意:日期需要正确格式化才能生效


完整查询:

SELECT  
    CAL_OWNER,
    CAL_TITLE,
    FROM_UNIXTIME (CAL_CREATED, '%m-%d-%y') AS CREATED_AT,
    FROM_UNIXTIME (RANGE_START, '%Y-%m-%d') AS DATE2BESEEN,
    CASE CAL_REFERRAL_TYPE
        WHEN 1 THEN 'NoReferral'
        WHEN 2 THEN 'CareyGuide'
        WHEN 3 THEN 'Education'
        WHEN 4 THEN 'Employment'
        WHEN 5 THEN 'Housing'
        WHEN 6 THEN 'Medical'
        ELSE 'NA'
    END AS REFERRALS
FROM  EGW_CAL
WHERE FROM_UNIXTIME(CAL_CREATED,'%Y-%m-%d') BETWEEN (NOW() - INTERVAL 30 DAY) AND NOW()
ORDER BY REFERRALS ASC;

答案 1 :(得分:1)

  • CAL_CREATED是UNIX时间戳,
  • NOW()将返回MySQL时间戳。

它们不会自动混合。所以使用

WHERE CAL_CREATED 
    BETWEEN UNIX_TIMESTAMP(NOW() - INTERVAL 30 DAY) AND UNIX_TIMESTAMP(NOW());

注意:

我不建议采取其他方式

WHERE FROM_UNIXTIME(CAL_CREATED) BETWEEN ...

因为MySQL在这种情况下不能使用索引。

答案 2 :(得分:0)

正确的where子句使用internval

WHERE   CAL_CREATED BETWEEN NOW() - interval 30 day AND NOW()

单引号的使用让人联想到Postgres。在MySQL中,它最终将now()的值视为整数。并从中减去字符串值“30天”。

now()被视为整数时,它还有小时,分钟和秒。所以你真的减去了30秒之类的东西。 Herenow()上的文档。