我使用laravel雄辩的关系和缓慢的查询执行问题,让我说我有两个表聊天(1百万记录)
线索(一半百万记录)
和我想查询聊天
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)
请检查上面的调试,你可以看到第一次查询将从数据库中获取50万行,这将需要很多时间,所以我应该怎么做才能加入查询??当使用其中有它是放置内部查询这是需要时间也查询与其中有
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` = ?)
既然您有50万行,我认为您应该加入您的表:
$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();
where group_id =1 AND chat_id in (result)
需要此复合索引:索引(组id、聊天id)