繁体   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