簡體   English   中英

Laravel Eloquent的慢MySQL查詢

[英]Slow MySQL query with Laravel Eloquent

我正在使用Laravel Eloquent並調試為什么此查詢需要這么長時間:

select count(*) as aggregate 
from `custom_products` 
where `hidden` = '0' 
and (`company_id` = '1')
and exists (
   select * from `categories` 
   inner join `categorizables` on `categories`.`id` = `categorizables`.`category_id` 
   where `custom_products`.`id` = `categorizables`.`categorizable_id`
   and `categorizables`.`categorizable_type` = 'App\Models\CustomProduct' 
   and `categories`.`deleted_at` is null) 
and exists (
   select * from `images` 
   where `custom_products`.`id` = `images`.`imageable_id` 
   and `images`.`imageable_type` = 'App\Models\CustomProduct' 
   and `images`.`deleted_at` is null) 
and `custom_products`.`deleted_at` is null

有時它運行非常緩慢:如您從調試欄中看到的該圖像中所示,它花費了17.46s:

打印調試欄

有人知道為什么嗎?

images imageable_idPRIMARY KEY嗎? 為每個表提供SHOW CREATE TABLE

custom_products上有哪些索引? 它需要

INDEX(company_id, hidden, deleted_at)

在另一個主題上,我認為您在'App\\Models\\CustomProduct'存在一個錯誤-反斜杠是轉義字符,而不是目錄分隔符。 可能您需要'App\\\\Models\\\\CustomProduct'

嘗試添加以下索引以優化查詢:

ALTER TABLE `categories` ADD INDEX `categories_idx_at_id` (`deleted_at`,`id`);
ALTER TABLE `categorizables` ADD INDEX `categorizables_idx_type_id_id` (`categorizable_type`,`category_id`,`categorizable_id`);
ALTER TABLE `custom_products` ADD INDEX `custom_products_idx_hidden_id_at` (`hidden`,`company_id`,`deleted_at`);
ALTER TABLE `custom_products` ADD INDEX `custom_products_idx_id` (`id`);
ALTER TABLE `images` ADD INDEX `images_idx_type_at_id` (`imageable_type`,`deleted_at`,`imageable_id`);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM