1、find_in_set()问题
find_in_set会使用全表扫描,导致查询效率很低
2、改进之前的语句
select * from `persons` where `logout` = '0' and FIND_IN_SET(unitcode, getChildList('%', 1));
---query time
---2.5s
复制代码3、改进之后的语句
select * from `persons` inner join (select getChildList('%', 1) unitlist) x on `unitlist`=`unitlist` and FIND_IN_SET(unitcode, unitlist) where `logout` = '0';
---query time
---0.06s
复制代码4、Laravel中的使用
public function scopeAtunit($query, $unitcode)
{
$unitcode = $unitcode ? $unitcode : '%';
return $query->join(DB::raw("(select getChildList('{$unitcode}', 1) unitlist) x"), function ($join) {
$join->on('unitlist', '=', 'unitlist')
->whereRaw('FIND_IN_SET(unitcode, unitlist)');
});
//return $query->whereRaw('FIND_IN_SET(unitcode, getChildList(?, 1))', [$unitcode]);
}
复制代码
本文探讨了find_in_set函数导致查询效率低的问题,并通过重构SQL查询来显著提高执行速度,从2.5秒降低到0.06秒。同时提供了一个Laravel示例,展示了如何在实际应用中实现这一优化。
3万+

被折叠的 条评论
为什么被折叠?



