我正在使用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.46秒才能运行:
任何人都知道为什么?
答案 0 :(得分:1)
images
。imageable_id
是PRIMARY KEY
?为每个表提供SHOW CREATE TABLE
。
custom_products
上有哪些索引?它需要
INDEX(company_id, hidden, deleted_at)
在另一个主题上,我认为你在'App\Models\CustomProduct'
中有一个错误 - 反斜杠是转义字符,而不是目录分隔符。可能你需要'App\\Models\\CustomProduct'
答案 1 :(得分:1)
尝试添加这些索引以优化查询:
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`);