15

我正在尝试在单个查询中选择 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
4

3 回答 3

25

要获取日期跨度之间的记录,请使用:

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

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

于 2010-04-21T16:05:29.490 回答
2

如果您创建的列类型是 int 那就试试这个

created<= UNIX_TIMESTAMP(DATE_ADD(CURDATE(),INTERVAL 5 DAY))')
于 2014-03-21T09:29:12.423 回答
1
WHERE created <= NOW() AND created >=NOW() - INTERVAL 5 DAY

或者最好只比较日期时间的 DATE 部分:

WHERE DATE(created) <= date(NOW()) AND 
  DATE(created) >= DATE(NOW() - INTERVAL 5 DAY)
于 2010-04-21T16:03:53.313 回答