我需要检查在过去“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个条目).
如果有人可以提供帮助,我会非常感激
最佳答案 尝试使用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;