我正在尝试获取所有产品(限额5),这些产品是过去7天的畅销产品(总销售额)。
我当前的数据库架构基本上是这样的:
- products
- id
- name
- price
- orders
- id
- purchased_at
- orders_products
- id
- products_id
- orders_id
- quantity
- paid_price
我正在寻找mysql语法。
提前致谢!
答案 0 :(得分:3)
这是一个相对简单的INNER JOIN
s序列,SUM()
的汇总quantity
乘以paid_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
我建议花些时间审核aggregate functions。