我有三个表格,其中包含以下相关属性:
我想整理一个"索引"比较自推出以来的前X周内每种产品(按类型和价格点)的销售情况。
到目前为止,我有这个:
select
product.product_name, ...
round(product_sales.total_sales / (product_sales_by_price_and_type.total_sales / product_sales_by_price_and_type.num_products),4) as 'Index'
from
products
inner join companies (on id...)
left join
(
select sum(week_sales_amount) as total_sales, product_id, ...
from sales
where sales.week_number between 'A' and 'B'
group by sales.product_id
) product_sales
left join
(
select company.id, product.price, product.type, sum(sales.week_sales_amount as total_sales, count(distinct product.id) as num_products
from products
inner join companies
left join sales
where sales.week_number between 'A' and 'B'
group by companies.id, products.price, products.type
having count(sales.week_number >= 'B')
) product_sales_by_price_and_type
以上工作正常,直到我需要添加额外的标准来计算滚动指数,例如对于每种产品,仅在其发布日期的x年内与其他产品(相同公司,产品价格和产品类型)的销售额进行比较。为了满足这一点,我将左连接转换为两个查询,即:
(
select sum(sales.week_sales_amount) as total_sales
from products
inner join companies
left join sales
where sales.week_number between 'A' and 'B'
**and products.launch_date >= (outer products.launch_date - 2 years)**
and companies.id = ...
and products.price = ...
and products.type = ...
group by companies.id, products.price, products.type
having count(sales.week_number >= 'B')
) product_sales_by_price_and_type
当然我必须做同样的计算(所以我从一个左连接变为两个查询。
有更好的方法吗?
在MySQL中,如果我使用左连接运行原始查询,它的持续时间为0.34秒,获取时间为0.07秒(我在本地日期基础上运行)。
使用相关子查询,持续时间实际上更快,为0.17秒,但获取时间上升到将近60秒。
有关如何优化此功能的任何建议吗?