简体   繁体   中英

Laravel 5.2 Eloquent query takes too long time to 'count'

I am using Laravel 5.2 with MySQL 5.6.33

When I check the DB query by applying dd(DB::getQueryLog()); , it returns as following:

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
]

As you can see the result, the "count" query has taken 22286ms to complete , but the same query of filtering data has took only 38.4ms. Where I need to look at to make faster this query? Need to change in the DB or Eloquent?

Edit:

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

Followings are explain output and my tables indexes 在此处输入图片说明

I found my error. The column agent_id should be indexed in the products table

use this query to count primary keys instead of * will keep you faster then *

select count(products.id) as aggregate from `products` as Products
INNER JOIN `agents` as Agent ON (Agent.id = Products.agent_id )
INNER JOIN productlocations as ProductLocations ON (ProductLocations.product_id = Products.id AND Agent .town_id = 674) 
INNER JOIN productagents as ProductAgents ON (ProductAgents.product_id = Products.id AND ProductAgents.product_status_id = "your input status Id") 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM