【问题标题】:Slow MySQL query with Laravel Eloquent使用 Laravel Eloquent 进行缓慢的 MySQL 查询
【发布时间】: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


【解决方案1】:

images.imageable_idPRIMARY KEY 吗?为每个表提供SHOW CREATE TABLE

custom_products 上有哪些索引?它需要

INDEX(company_id, hidden, deleted_at)

在另一个主题上,我认为您在'App\Models\CustomProduct' 中有一个错误——反斜杠是转义字符,而不是目录分隔符。可能你需要'App\\Models\\CustomProduct'

【讨论】:

    【解决方案2】:

    尝试添加这些索引来优化查询:

    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`);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多