我正在尝试过滤大行表上的搜索结果。我尝试了whereHas和WhereIn两种查询都很慢。
有3个表,places
,categories
,locations
。
地点-类别和地点-地点之间的关系都属于belongsToMany,因此还有两个枢纽分析表place_category
和place_location
。
places表包含约10万行
位置-类别表包含约65万行, place_category.place_id 和 places.brand_id 列已编入索引
位置-位置表包含约550k以上的行, place_location.place_id 和 place_location.location_id 列已编入索引
我尝试过的查询
Place::whereHas('locations',function($query) use($city) {
$query->where('locations.id',$city->id);
})
->whereHas('categories',function($query){
$query->where('categories.id',65);
})->groupBy('places.brand_id'->take(4)->get()
最慢的地方,大约需要3s
Place::whereIn('places.id',function($query) use($city) {
$query->from('place_location')->select('place_location.place_id')->where('place_location.location_id',$city->id);
})
->whereIn('places.id',function($query){
$query->from('place_category')->select('place_category.place_id')->where('place_category.category_id',65);
})->groupBy('places.brand_id'->take(4)->get()
WhereIn大约需要2.6秒
Place::join('place_location',function ($join) use($city){
$join->on('place_location.place_id','=','places.id')
->where('place_location.location_id',$city->id);
})
->join('place_category',function ($join){
$join->on('place_category.place_id','places.id')
->where('place_category.category_id',65);
})->groupBy('places.brand_id')->take(4)->get();
加入大约需要1-2秒。
这些查询太慢了
我知道导致该问题的问题之一是groupBy,最后一次使用join查询,还有其他方法可以缩短查询时间吗?