检索日期为X天前的MySQL记录

时间:2015-04-11 15:10:27

标签: mysql date

您好我正试图从MySQL数据库中提取一些记录,我已尝试解决方案,例如:

SELECT o.id_order, o.reference, o.id_customer, DATE_FORMAT(o.invoice_date, '%m%d%y') AS 'invoice_date'
FROM ps_orders AS o
WHERE DATE(o.invoice_date) = CURDATE() - INTERVAL 100 DAY;

SELECT o.id_order, o.reference, o.id_customer, o.invoice_date
FROM ps_orders AS o
WHERE o.invoice_date = DATE_SUB(CURDATE(), INTERVAL 30 DAY);

但我一直得到0结果。

格式:

o.invoice_date

是2013-04-06 02:02:12(YYYY-MM-DD HH:II:SS)。

我不知道为什么我一直得到0结果。当我尝试使用此查询时:

SELECT o.id_order, o.reference, o.id_customer, o.invoice_date
FROM ps_orders AS o
WHERE o.invoice_date < CURDATE() - INTERVAL 30 DAY
ORDER BY o.invoice_date DESC;

有效,但我只想从 x DAY前(完全)获取数据。有人能指出我正确的方向。谢谢你的帮助...

1 个答案:

答案 0 :(得分:0)

最好的方法是:

WHERE o.invoice_date >= CURDATE() - INTERVAL 30 DAY AND
      o.invoice_date < CURDATE() - INTERVAL 29 DAY

这允许查询引擎在o.invoice_date上使用索引。