开发者

SQL query to show most ordered product

开发者 https://www.devze.com 2022-12-19 19:51 出处:网络
I have this table structure 开发者_运维知识库Product product_id (PK) name Order_Detail order_detail_id

I have this table structure

开发者_运维知识库Product

product_id (PK)

name

Order_Detail

order_detail_id

product_id

quantity

Example data

Product :

1 product1

2 product2

3 product3

4 product4

5 product5

Order_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 1

Please 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
0

精彩评论

暂无评论...
验证码 换一张
取 消