MySQL DATE_ADD用法,5天间隔

时间:2010-04-21 15:59:34

标签: mysql date intervals

我正在尝试在单个查询中选择5天内的订单总金额($)和发票计数。我似乎无法让这件事发生。我当前的查询在这里......

SELECT
    COUNT(id) as invoice_count,
    SUM(orderTotal) as orders_sum,
    UNIX_TIMESTAMP(created) as created
FROM ids_invoice
WHERE DATE_ADD(created, INTERVAL +1 DAY)
AND userId = 23 LIMIT 5'

我不完全确定DATE_ADD是我正在寻找的正确功能。

目前我正在......

Array ( 
    [0] => Array ( 
        [invoice_count] => 420
        [orders_total] => 97902.90
        [created] => 1252596560
    )
)

Array ( 
    [0] => Array ( 
        [invoice_count] => 68
        [orders_total] => 14193.20
        [created] => 1262900809
    )
)

我想得到更像......

Array ( 
    [0] => Array ( 
        [invoice_count] => 18
        [orders_total] => 4902.90
        [date] => 04-19-2010
    )
)

Array ( 
    [0] => Array ( 
        [invoice_count] => 12
        [orders_total] => 5193.20
        [date] => 04-20-2010
    )
)

我对mysql日期函数相当新,所以也许我错过了通过mysql文档时所需的函数。

更新 我已经更新了我的查询......对于有发票的每一天,这仍然没有排成一行。当20号发票符合userId标准时,它只会从19号开始提取发票。

SELECT
    COUNT(id) as invoice_count,
    SUM(orderTotal) as orders_sum,
    UNIX_TIMESTAMP(created) as created
FROM ids_invoice
WHERE
    created BETWEEN "2010-04-19 00:00:00" AND DATE_ADD("2010-04-19 00:00:00", INTERVAL +5 DAY) AND
    userId = 17

3 个答案:

答案 0 :(得分:21)

要获取日期范围之间的记录,请使用:

WHERE created BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 5 DAY)

此示例将为您提供今天和未来几天之间的记录(假设今天存在,包括时间)。如果你想要回到过去,请查看DATE_SUB。

答案 1 :(得分:2)

如果您创建的列类型是int,那么只需尝试一下

created<= UNIX_TIMESTAMP(DATE_ADD(CURDATE(),INTERVAL 5 DAY))')

答案 2 :(得分:0)

WHERE created <= NOW() AND created >=NOW() - INTERVAL 5 DAY

或者比较日期时间的DATE部分会更好:

WHERE DATE(created) <= date(NOW()) AND 
  DATE(created) >= DATE(NOW() - INTERVAL 5 DAY)