I have this table structure
开发者_运维知识库Product
product_id (PK) nameOrder_Detail
order_detail_id product_id quantityExample data
Product :
1 product1 2 product2 3 product3 4 product4 5 product5Order_Detail : 1 3 2
2 3 1 3 3 1 4 2 1 5 2 1 6 1 1 7 4 1 8 5 1 9 1 1 10 2 1 11 3 1Please help me to get top 3 ordered product based on how many times the product ordered ?
I think this migth work:
SELECT p.`product_id`, p.`name`, SUM(o.`quantity`) AS quantity
FROM `Order_Detail` AS o
INNER JOIN `Product` AS p
ON o.`product_id` = p.`product_id`
GROUP BY o.`product_id`
ORDER BY SUM(o.`quantity`) DESC, p.`name` ASC
LIMIT 3
精彩评论