[英]Laravel Join tables and group by sum query too slow
I am using Laravel query builder to get desired results from database.我正在使用 Laravel 查询构建器从数据库中获取所需的结果。 The following query if working perfectly but taking too much time to get results.
以下查询是否工作正常但需要太多时间才能获得结果。 Can you please help me with this?
你能帮我解决这个问题吗?
select
`amz_ads_sp_campaigns`.*,
SUM(attributedUnitsOrdered7d) as order7d,
SUM(attributedUnitsOrdered30d) as order30d,
SUM(attributedSales7d) as sale7d,
SUM(attributedSales30d) as sale30d,
SUM(impressions) as impressions,
SUM(clicks) as clicks,
SUM(cost) as cost,
SUM(attributedConversions7d) as attributedConversions7d,
SUM(attributedConversions30d) as attributedConversions30d
from
`amz_ads_sp_product_targetings`
inner join `amz_ads_sp_report_product_targetings` on `amz_ads_sp_product_targetings`.`campaignId` = `amz_ads_sp_report_product_targetings`.`campaignId`
inner join `amz_ads_sp_campaigns` on `amz_ads_sp_report_product_targetings`.`campaignId` = `amz_ads_sp_campaigns`.`campaignId`
where
(
`amz_ads_sp_product_targetings`.`user_id` = ?
and `amz_ads_sp_product_targetings`.`profileId` = ?
)
group by
`amz_ads_sp_product_targetings`.`campaignId`
Result of Explain SQL解释 SQL 的结果
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE amz_ads_sp_report_product_targetings ALL campaignId NULL NULL NULL 50061 Using temporary; Using filesort
1 SIMPLE amz_ads_sp_campaigns ref campaignId campaignId 8 pr-amz-ppc.amz_ads_sp_report_product_targetings.ca... 1
1 SIMPLE amz_ads_sp_product_targetings ref campaignId campaignId 8 pr-amz-ppc.amz_ads_sp_report_product_targetings.ca... 33 Using where
Your query could benefit from several indices to cover the WHERE
clause as well as the join conditions:您的查询可以从几个索引中受益,以涵盖
WHERE
子句以及连接条件:
CREATE INDEX idx1 ON amz_ads_sp_product_targetings (
user_id, profileId, campaignId);
CREATE INDEX idx2 ON amz_ads_sp_report_product_targetings (
campaignId);
CREATE INDEX idx3 ON amz_ads_sp_campaigns (campaignId);
The first index idx1
covers the entire WHERE
clause, which might let MySQL throw away many records on the initial scan of the amz_ads_sp_product_targetings
table.第一个索引
idx1
覆盖了整个WHERE
子句,这可能会让 MySQL 在amz_ads_sp_product_targetings
表的初始扫描时丢弃许多记录。 It also includes the campaignId
column, which is needed for the first join.它还包括第一次加入所需的
campaignId
列。 The second and third indices cover the join columns of each respective table.第二个和第三个索引覆盖每个表的连接列。 This might let MySQL do a more rapid lookup during the join process.
这可能让 MySQL 在连接过程中进行更快速的查找。
Note that selecting amz_ads_sp_campaigns.*
is not valid unless the campaignId
of that table be the primary key.请注意,选择
amz_ads_sp_campaigns.*
是无效的,除非campaignId
该表的是主键。 Also, there isn't much else we can do speed up the query, as SUM
, by its nature, requires touching every record in order to come up the result sum.此外,我们不能做太多其他事情来加速查询,因为
SUM
其性质而言,需要接触每条记录才能得出结果总和。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.