我首先计划使用多个查询和一些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是错误的(它选择了第一个订单而不是最后一个订单?)
是否需要“限制1”?
答案 0 :(得分: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')