【问题标题】:Laravel Eloquent Making Query Execution SlowLaravel Eloquent 使查询执行变慢
【发布时间】:2021-06-23 06:23:04
【问题描述】:

我正在使用 laravel 雄辩的关系并且有缓慢的查询执行问题 假设我有两张桌子 聊天(100 万条记录)
潜在客户(50 万条记录)
我想查询使用的群组的聊天和潜在客户数据

 lead::select("chat_lead_id")->with([chats=>function($q){
    $q->select('chat_id',"group_id")->where("group_id"=>1)
    })

查询调试 第一个查询:

result =select chat_lead_id from leads 

第二次查询

select chat_id,group_id from chats  where group_id =1 AND chat_id in (result)

请检查上面的调试,您可以看到 First Query 将从数据库中获取 50 万行,这将花费很多时间 那么我应该怎么做才能加入查询? 使用 WhereHas 时,它正在放置内部查询,这也需要时间 查询 WhereHas

select * from `gc_od_leads`
    where exists (select * from `gc_od_chat`
            where `gc_od_leads`.`leads_chat_id`
                = `gc_od_chat`.`chat_id`
              and `chat_group_id` = ?)

【问题讨论】:

  • 您正在寻找whereHas 方法。
  • whereHas 正在做内部查询,这使得速度更慢
  • 您可能需要为 group_id 和 chat_id 添加索引。另一种选择是进行左连接而不是子查询,这将减少查询的数量。
  • 请检查我更新的问题与 wherehas 查询你的意思是我需要继续加入而不是关系

标签: php mysql database laravel eloquent


【解决方案1】:

因为你有 50 万行,我认为你应该只 join 你的表:

 $values=lead::query()->join('chats','leads.chat_lead_id','=','chats.chat_id')
            ->where("group_id",=,1)->select(["chat_lead_id",'chat_id',"group_id"])->get();

【讨论】:

  • 我正在使用 join 我只是想确认使用 join 是唯一的解决方案,并且在这些情况下没有雄辩的解决方案吗??
  • 我发布了这个问题,人们开始说我错了stackoverflow.com/questions/66815015/… 这里
  • join 是进行此查询的最快方式,其他方式要慢得多
【解决方案2】:
where group_id =1 AND chat_id in (result)

需要这个复合索引:INDEX(group_id, chat_id)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-17
    • 2019-04-27
    • 2018-01-30
    • 2018-02-27
    • 2019-07-27
    • 2017-10-22
    • 2016-12-18
    相关资源
    最近更新 更多