【发布时间】:2018-04-19 20:14:16
【问题描述】:
我正在使用 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 秒,正如您在调试栏的这张图片中看到的那样:
有人知道为什么吗?
【问题讨论】:
-
使用
explain(dev.mysql.com/doc/refman/5.7/en/explain.html) 找出运行缓慢的查询并进行优化 -
这对你来说是经典的雄辩。按照@Ben 所说的进行解释,然后使用连接重做查询并再次进行解释。惊叹于速度差异。之后转到查询生成器,不要回头。你的桌子越大,它变得越糟。顺便说一句,您是否在表上设置了索引?这也很重要
-
Rafael 您正在执行 2 个“存在”查询,这些查询实际上是子查询,并且您在两者中都执行了 select*。您能否更好地连接这些子查询,并可能使用 where() 过滤掉结果
标签: php mysql laravel performance eloquent