我有以下内容,但由于GROUP BY
未添加群组用户ID的总收入,因此无法获得正确的总计。
SELECT
users.id,
Count(orders.id) AS total_orders,
SUM(item_orders.item_price * item_orders.quantity) AS total_rev
FROM
orders
LEFT JOIN
users ON orders.user_id = users.id
LEFT JOIN
item_orders ON item_orders.order_id = orders.id
WHERE
orders.date >= '2015-10-06 00:00:00' AND orders.date <= '2016-03-23 23:59:59'
GROUP BY
users.id -- ignores duplicate ids, doesn't sum total_rev for those
ORDER BY
total_rev DESC
LIMIT 0,25
我想使用WITH ROLLUP
来解决这个问题,但是当我使用WITH ROLLUP
时,我无法使用ORDER BY
而我无法使用别名GROUP BY
订购包含我的每个用户ID总数。
SELECT
users.id,
Count(orders.id) AS total_orders,
SUM(item_orders.item_price * item_orders.quantity) AS total_rev
FROM
orders
LEFT JOIN
users ON orders.user_id = users.id
LEFT JOIN
item_orders ON item_orders.order_id = orders.id
WHERE
orders.date >= '2015-10-06 00:00:00' AND orders.date <= '2016-03-23 23:59:59'
GROUP BY
users.id, total_rev DESC WITH ROLLUP -- does not work because total_rev is an alias!
LIMIT 0,25
有关如何使其发挥作用的任何建议?我在DB中这样做有意义吗?我试图通过让数据库预先分配来节省资源,这样我就可以在我的应用程序中进行分页。
编辑:正如下面评论中提到的xjstratedgebx,第一个查询正常,没有理由使用WITH ROLLUP
。第一个查询也可以缩短:
SELECT
orders.user_id,
Count(orders.id) AS total_orders,
SUM(item_orders.item_price * item_orders.quantity) AS total_rev
FROM
orders
LEFT JOIN
item_orders ON item_orders.order_id = orders.id
WHERE
orders.date >= '2015-10-06 00:00:00' AND orders.date <= '2016-03-23 23:59:59'
GROUP BY
orders.user_id
ORDER BY
total_rev DESC
LIMIT 0,25