我正在使用laravel eloquent,并且有数据库中有数千条记录的情况,所以当使用eloquent关系时,我的查询执行速度很慢。我应该避免在这些饱和度或任何其他方式使用eloquent吗?
下面是mysql查询
$leads=Lead::select($col)
->join("gc_od_leads_detail as ld", "gc_od_leads.leads_id", "=", "ld.ld_leads_id")
->join("gc_od_chat as c", "gc_od_leads.leads_chat_id", "=", "c.chat_id")
->join("gc_od_group as g", "c.chat_group_id", "=", "g.group_octachat_id")
->where('c.chat_tags','sales')
->whereIn('c.chat_group_id',$filter['groups']);
if(!empty($filter['keyword'])) {
$leads=$leads->where(function ($q) use ($filter) {
$q->where('ld_name','like', "%".$filter['keyword']."%")
->orWhere('ld_email','like', "%".$filter['keyword']."%")
->orWhere('ld_phoneno','like', "%".$filter['keyword']."%");
});
}
if(!empty($filter['startDate']) && !empty($filter['endDate'])){
$leads=$leads->whereBetween('leads_created_date', [$filter['startDate']." 00:00:00",$filter['endDate']." 23:59:59"]);
}
$leads=$leads->orderBy('leads_created_date','desc');
return $leads;
}
我在边留言和聊天表上有超过50万条录音。我更改了eloquent中的查询并进行了调试
查询:
Lead::select('leads_id','leads_chat_id')->with(["detail"=>function($q){
$q->select("ld_leads_id");
}])->with(["chat"=>function($q){
$q->select("chat_id")->where(['chat_status'=>1]);
}])->where("leads_status",1)->get();
Debuging Ouput
array:3 [▼
0 => array:3 [▼
"query" => "select `leads_id`, `leads_chat_id` from `gc_od_leads` where `leads_status` = ?"
"bindings" => array:1 [▼
0 => 1
]
"time" => 14.85
]
1 => array:3 [▼
"query" => "select `ld_leads_id` from `gc_od_leads_detail` where `gc_od_leads_detail`.`ld_leads_id` in (2278918, 2278919, 2278920, 2278921, 2278922, 2278923, 2278924, 22789 ▶"
"bindings" => []
"time" => 0.59
]
2 => array:3 [▼
"query" => "select `chat_id` from `gc_od_chat` where `gc_od_chat`.`chat_id` in (3496457, 3496458, 3496459, 3496460, 3496461, 3496462, 3496463, 3496464, 3496465, 3496466, 34 ▶"
"bindings" => array:1 [▶]
"time" => 4.21
]
]
在上面的输出中,您可以看到它首先获取所有销售线索的记录,然后转到销售线索详细信息和聊天表如果我只想找出聊天状态为1的销售线索,它仍然会查询所有销售线索这就是我的查询速度变慢的原因
我想这会节省时间和空间,这就是我的问题,我想很多人都有同样的问题,但没有人讨论这一点
发布于 2021-03-26 19:00:25
让我们来看一下其中的一部分。
if(!empty($filter['keyword'])) {
$leads=$leads->where(function ($q) use ($filter) {
$q->where('ld_name','like', "%".$filter['keyword']."%")
->orWhere('ld_email','like', "%".$filter['keyword']."%")
->orWhere('ld_phoneno','like', "%".$filter['keyword']."%");
});
}
这种关键字匹配方案天生就很慢,而且是灾难性的。无论是在雄辩的SQL中还是在本地SQL中,它都很慢。如果不做full table scan,它就不可能在MySQL中工作。也就是说,它必须检查表中的每一行以查找匹配项,并且在MySQL中不能利用任何索引查找方案。为什么?
column LIKE 'constant%'
可以查看column
上的索引,并快速找到以'constant'
开头的任何值。但
column LIKE '%constant%'
必须查看表中的每个值。前导%
使索引查找变得无用。
在MySQL中,明智的做法是研究MySQL's FULLTEXT searching作为处理关键字查找的一种方式。(最新版本的postgreSQL可以使用不同类型的索引直接处理这类查询,但不能使用MySQL。)
https://stackoverflow.com/questions/66815015
复制相似问题