SQL按销售数量为每位用户获得前3个订购最多的产品

时间:2018-04-24 08:52:16

标签: mysql sql e-commerce

我正在研究一个学校项目,其中一个是用于销售啤酒的电子商务网站。

我需要为订购了某些东西的每个用户提供前3个最有序的产品。我的数据库包括4个表:用户,产品,订单和order_detail。该图是:

https://imgur.com/a/PofTxjQ

我想我必须加入所有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

数据库脚本:https://pastebin.com/BvQLGqur

1 个答案:

答案 0 :(得分:1)

为了限制返回的行只显示为每个用户订购的前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`;