-1

我正在尝试获取过去 7 天的畅销产品(总销售额)的所有产品(限制 5)。

我当前的数据库模式基本上是这样的:

- products
 - id
 - name
 - price

- orders
 - id
 - purchased_at

- orders_products
 - id
 - products_id
 - orders_id
 - quantity
 - paid_price

我正在寻找 mysql 语法。

提前致谢!

4

1 回答 1

3

这是一个相对简单的 s 序列,其中包含乘以INNER JOIN的聚合:SUM()quantitypaid_price

SELECT
  p.name,
  /* aggregate SUM() of orders_products qty * price */
  SUM(op.quantity * op.paid_price) AS total_sale_price
FROM
  products
  /* Join through orders_products (which gives the quantity) */
  INNER JOIN orders_products op ON p.id = op.products_id
  /* ...to orders (which provides the date) */
  INNER JOIN orders o ON op.orders_id = o.id
/* The last week... */
WHERE o.purchased_at >= (CURDATE() - INTERVAL 7 DAY)
GROUP BY p.name
/* In descending order of quantity, only the top 5 */
ORDER BY total_paid_price DESC LIMIT 5

我建议花一些时间查看聚合函数

于 2013-02-13T17:41:07.773 回答