Laravel联接表和按和查询分组太慢

时间:2020-10-22 14:28:35

标签: mysql laravel

我正在使用Laravel查询生成器从数据库中获取所需的结果。以下查询是否工作正常,但花费太多时间才能获得结果。你能帮我吗?

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`

解释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

1 个答案:

答案 0 :(得分:1)

您的查询可以受益于多个索引,以覆盖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);

第一个索引idx1覆盖了整个WHERE子句,这可能使MySQL在amz_ads_sp_product_targetings表的初始扫描中丢弃许多记录。它还包括campaignId列,这是首次连接所必需的。第二和第三索引覆盖每个相应表的联接列。这可能会使MySQL在联接过程中进行更快速的查找。

请注意,除非该表的amz_ads_sp_campaigns.*是主键,否则选择campaignId是无效的。另外,我们没有太多其他方法可以加快查询的速度,因为SUM本质上要求触摸每条记录以得出结果总和。