获取带有时间戳的最近30天订单

时间:2017-02-20 22:22:34

标签: mysql

Table Orders
order_id
timestamp

Table OrderLines
orderlines_id
order_id

示例数据

订单表

order_id tmestamp 
       1 2017-01-10 17:47:25
       2 2017-01-21 17:53:39
       3 2017-01-21 17:55:04
       4 2017-01-21 18:16:30 
       5 2016-12-21 18:17:12

示例数据订单行表

orderlines_id order_id
            1        1
            2        2
            3        3
            4        4
            5        5

我希望从今天的日期和当前时间开始查看last 30天的订单。我不确定我的查询是否正常工作。

方法1:

SELECT 
o.timestamp
,ol.retail_price
FROM orders o,
mpos.orderlines ol
where o.timestamp between now() - INTERVAL 30 day and now()
group by o.order_id;

根据下面的示例数据,它只会返回一条记录,因为它应该返回多个记录。

2017-01-10 17:47:25 

方法2:

SELECT 
o.timestamp
,ol.retail_price
FROM orders o,
mpos.orderlines ol
where o.order_id = ol.order_id
AND ol.order_status_id = 1
AND now() - INTERVAL 1 MONTH;

此查询会返回更多行,但也会返回超过今天日期和时间前30天的数据。请看下面的

结果:

   2017-01-10 17:47:25
   2017-01-21 17:53:39
   2017-01-21 17:55:04
   2017-01-21 18:16:30 
   2016-12-21 18:17:12 

1 个答案:

答案 0 :(得分:-1)

那是因为在第二种方法中你没有检查时间戳是否在一段时间内......

试试这个,看看它是否给你相同的结果

SELECT 
o.timestamp
,ol.retail_price
FROM orders o,
mpos.orderlines ol
where o.order_id = ol.order_id
AND ol.order_status_id = 1
AND ol.timestamp between now() and now() - INTERVAL 1 MONTH;
相关问题