Laravel 5.2 Eloquent查询需要很长时间来计算'

时间:2016-09-23 12:16:40

标签: php mysql laravel-5 laravel-5.2

我正在使用Laravel 5.2和MySQL 5.6.33

当我通过应用dd(DB::getQueryLog());检查数据库查询时,它返回如下:

array:14 [▼
  0 => array:3 [▼
  "query" => "select count(*) as aggregate from `products` where exists (select * from `agents` where `products`.`agent_id` = `agents`.`id`) and exists (select * from `productlocations` where `productlocations`.`product_id` = `products`.`id` and `town_id` = ?) and exists (select * from `productagents` where `productagents`.`product_id` = `products`.`id` and `product_status_id` = ?)"
  "bindings" => array:2 [▼
        0 => "674"
        1 => "1"
  ]
  "time" => 22286.26
  ]

  1 => array:3 [▼
  "query" => "select * from `products` where exists (select * from `agents` where `products`.`agent_id` = `agents`.`id`) and exists (select * from `productlocations` where `productlocations`.`product_id` = `products`.`id` and `town_id` = ?) and exists (select * from `productagents` where `productagents`.`product_id` = `products`.`id` and `product_status_id` = ?) order by `id` desc limit 10 offset 0"
  "bindings" => array:2 [▼
        0 => "674"
        1 => "1"
  ]
  "time" => 38.4
  ]

  2 => array:3 [▼
  "query" => "select * from `agents` where `agents`.`id` in (?)"
  "bindings" => array:1 [▶]
  "time" => 0.58
]

你可以看到结果,"计数"查询已完成22286ms,但过滤数据的相同查询只花了38.4ms。我需要在哪里查看以加快此查询的速度?需要更改DB还是Eloquent?

编辑:

explain 
select * from `products` where exists 
    (select * from `agents` where `products`.`agent_id` = `agents`.`id`) 
and exists 
    (select * from `productlocations` where `productlocations`.`product_id` = `products`.`id` and `town_id` = 674) 
and exists 
    (select * from `productagents` where `productagents`.`product_id` = `products`.`id` and `product_status_id` = 1) 
order by `id` desc limit 10 offset 0

以下是解释输出和我的表索引 enter image description here

2 个答案:

答案 0 :(得分:0)

我发现了我的错误。列agent_id应在products

中编入索引

答案 1 :(得分:0)

使用此查询来计算主键,而不是*将使您比*

更快
SELECT FROM raw re WHERE re.class_ids LIKE (regex)