我有这个表结构
产品
product_id(PK)
名称
Order_Detail
order_detail_id
PRODUCT_ID
量
示例数据
产品:
1产品1
2产品2
3产品3
4产品4
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
请根据产品订购的次数帮助我获得前三名订购产品?
答案 0 :(得分:1)
我认为这可行:
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