mysql - SQL 根据销售数量获取每个用户订购最多的前 3 个产品

标签 mysql sql e-commerce

我正在开展一个学校项目,其想法是建立一个销售啤酒的电子商务网站。

我需要为每个订购过商品的个人用户获取订购最多的前 3 个产品。我的数据库包括 4 个表:users、products、orders 和 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

最佳答案

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

相关文章:

php - 带有 'now() + INTERVAL' 的 INSERT 语句在具有命名占位符的 PDO 中插入 000

mysql - 如何以mysql中给定的格式获取mysql中的当前日期-1?

php - 是否有必要使用 mysql_real_escape_string() 将图像导入 mysql?

java - 在Java中的静态方法中创建SQLite连接

java - 为同一网络上连接的一组系统创建公共(public)数据库连接

php - 添加到购物车不适用于 magento 中的子商店

MySQL 查询绘制器

mysql - 即使在增加列长度后 MySQL 表上的算术溢出

php - Magento - 初学者概念 - 主题结构

magento - 在付款确认之前阻止 Magento 清空购物车?