MySQL 计数分组依据
我有 3 个表,订单(orders_id,日期,...),产品(product_id,product_name,product_price)和 order_products(product_id,orders_id,product_id,products_quantity),我需要对产品进行分组,以便它们按产品显示,每个产品的总数量,以便网店经理更容易了解每个产品已订购多少件商品。
我在思考正确的 sql 语法时遇到了一些麻烦,我不断遇到 group by 问题,我需要一些帮助。
这就是我到目前为止所做的
select *, op.products_quantity as pquant, count(*) as `count`
from orders o
left join orders_products op on o.orders_id = op.orders_id
left join products p on op.products_id = p.products_id
group by op.orders_products_id
order by op.products_id desc;
I have 3 tables, orders(orders_id, date, ...), products (product_id, product_name, product_price) and order_products (product_id, orders_id, product_id, products_quantity) and I need to group the products so that they are displayed by product and total quantity per product to make it easier for the eshop manager to know how many items per product have been ordered.
I'm having a little bot of trouble thinking of the correct sql syntax, I keep bumping into group by issues and i'd like some help.
This is what I've done so far
select *, op.products_quantity as pquant, count(*) as `count`
from orders o
left join orders_products op on o.orders_id = op.orders_id
left join products p on op.products_id = p.products_id
group by op.orders_products_id
order by op.products_id desc;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
看看你有什么,你正在计算订单,而不是对订单数量求和。
所以,
如果你有
订单,
你想要
在这种情况下你想做的,
我不太明白orders_products和orders之间的区别是什么。
也许一些样本数据会有帮助?
Looking at what you have, you're counting orders, not summing the quantity of the orders..
So
if you had
orders
You wanted
in which case you'd want to do
I didnt quite see what the differende between orders_products and orders was.
Maybe a bit of sample data would help?
如果您需要每个产品的总数量和总订单,则可以按以下方式执行
SELECT p.*,op.total_order,op.total_quantity FROM PRODUCT LEFT JOIN (SELECT COUNT(*) AS total_order, SUM(quantity) AS total_quantity FROM order_products GROUP BY Product_id) AS op ON p.id = op.product_id
If you need Total quantity and total orders per product than you can do that in following way
SELECT p.*,op.total_order,op.total_quantity FROM PRODUCT LEFT JOIN (SELECT COUNT(*) AS total_order, SUM(quantity) AS total_quantity FROM orders_products GROUP BY product_id) AS op ON p.id = op.product_id
这应该可行,使用 SUM,而不是 COUNT:
This should work, use SUM, not COUNT: