【发布时间】: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