我正在开展一个学校项目,其想法是建立一个销售啤酒的电子商务网站。
我需要为每个订购过商品的个人用户获取订购最多的前 3 个产品。我的数据库包括 4 个表:users、products、orders 和 order_detail。示意图为:
我想我必须加入所有 4 个表才能获取该信息,但我无法找出正确的方法。这是我生成的:
SELECT u.username, p.`id` AS productId, p.`name`, od.`quantity` AS quantity
FROM `order_detail` AS od
INNER JOIN `products` AS p
INNER JOIN `users` AS u
ON od.`product_id` = p.`id`
GROUP BY od.`order_id`, p.name
ORDER BY od.`quantity` DESC, p.`name` ASC
最佳答案
为了限制返回的行以仅显示每个用户订购的前 3 个产品,您需要在 order_detail 上使用带有 limit 子句的子查询。
除此之外,它只是 4 个表之间的简单连接。
SELECT
a.`user_name`,
d.`id` as `product_id`,
d.`name` as `product_name`,
SUM(c1.`quantity`) as `total_quantity`,
d.`price` as `product_price`,
d.`price` * SUM(c1.`quantity`) as `total_spent`
FROM `users` a
JOIN `orders` b
ON b.`user_id` = a.`id`
JOIN (SELECT c.`order_id`, c.`product_id`, SUM(c.`quantity`) as `num_ordered`
FROM `order_detail` c
ORDER BY `num_ordered` DESC
LIMIT 3) as c1
ON c1.`order_id` = b.`id`
JOIN `products` d
ON d.`id` = c1.`product_id`
GROUP BY a.`id`,d.`product_id`
ORDER BY a.`user_name`,`total_quantity` DESC, d.`name`;
关于mysql - SQL 根据销售数量获取每个用户订购最多的前 3 个产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49997301/