0

我首先计划使用多个查询和一些 PHP 来执行此操作。

我想做的是抓取特定用户上次下订单的时间,用户有多少订单,他支付的总金额/成本/计数是多少。

我试过的是这个SQL:

SELECT `orders`.`date_created`, 
SUM(total_count) as total_sum, 
COUNT(id) AS total_orders 
FROM `orders` 
WHERE `user_id` = '96838' 
AND (`status` = 'new' OR `status` = 'delivered') 
ORDER BY `orders`.`date_created` DESC
LIMIT 1

我从上面的期望是:

total_sum = total count/amount of all the orders that the user has.
total_orders = total orders
date_created = grab the last orders date_created, so we can know when the last time was.

当我今天运行上面的 SQL 时,我确实收到了正确的 total_sum 和 total_orders 值,但是 date_created 是错误的(它选择了第一个订单而不是最后一个?)

“LIMIT 1”是必要的吗?

4

1 回答 1

1

如果我了解您的需求,则无需分组-只需获取最大日期即可:

SELECT
    MAX(date_created) as last_order_date, 
    SUM(total_count) as total_sum, 
    COUNT(id) AS total_orders 
FROM
    `orders` 
WHERE
    `user_id` = '96838' 
    AND
    `status` IN ('new', 'delivered')
于 2013-10-22T11:25:08.327 回答