Are you using indexing, there was just a discussion on this, probably on very same page.
Slow MySQL query with Laravel Eloquent
I'm using Laravel Eloquent and debuging why this query is taking so long:
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
Sometimes it runs very slow: it tooks 17.46s to run as you see in this image from debugbar:
print of debugbar with the explain:
https://i.stack.imgur.com/GgZU9.png
Anyone knows why?
Yes, I'm using indexes as you can see in the image with the explain.
It looks like you only have a single index, when you really need many more.
Anything that is used in a WHERE needs to be indexed if there is a lot of data in the tables.
Please watch these videos: https://serversforhackers.com/laravel-perf/mysql-indexing-one
Please or to participate in this conversation.