MySQL函数find_in_set优化使用

本文探讨了find_in_set函数导致查询效率低的问题,并通过重构SQL查询来显著提高执行速度,从2.5秒降低到0.06秒。同时提供了一个Laravel示例,展示了如何在实际应用中实现这一优化。

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]);
    }
复制代码
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值