96秒sql语句优化

select c.*,max(cb.last_follow_time) as last_follow_time,cb.create_time as block_create_time from c_block cb 
left join customer c on c.id=cb.customer_id 
where cb.staff_id=76 and cb.give_up_time is null and cb.customer_id not in (
    select customer_id from bill_staff bs 
    left join bill_customer bc on bs.b_id=bc.b_id 
    where bs.staff_id=76 and customer_id is not null
) and cb.last_follow_time >-863999998580524166 and cb.customer_type in (1) and (c.tel like '%18846836939%' or c.id in (
    select c_id from c_contact where c_mobile like '%18846836939%' or c_workphone like '%18846836939%'
)) group by cb.customer_id order by max(cb.last_follow_time) desc LIMIT 0,10; 

# Query_time: 96.351328 Lock_time: 0.000313 Rows_sent: 10 Rows_examined: 119820131




第1步:分析sql:执行时间96秒,搜索119820131条数据,返回10条,大量检索被浪费。语句中子查询非常多。由查询分析可见,多条子查询均引起笛卡尔积。

第2步:第一个子查询加索引,从4324条检索缩小到2条

ALTER TABLE `c_contact` ADD INDEX(`c_workphone`);
ALTER TABLE `c_contact` ADD INDEX(`c_mobile`);


第3步:第二个子查询加索引

ALTER TABLE `bill_customer` ADD INDEX(`b_id`);
ALTER TABLE `bill_customer` ADD INDEX(`customer_id`);



第4步:第3个子查询加索引,此时可见两个子查询的数量已大福下降

ALTER TABLE `bill_staff` ADD INDEX(`b_id`);


第5步:搜索中电话全部改为精确搜索,此处修改了业务逻辑,搜索电话的情况,很少有模糊搜索,所以直接用全等于。最后搜索时间为0.003秒

select c.*,max(cb.last_follow_time) as last_follow_time,cb.create_time as block_create_time from customer_block cb left join customer c on c.id=cb.customer_id where cb.staff_id=76 and cb.give_up_time is null and cb.customer_id not in (select customer_id from bill_staff bs left join bill_customer bc on bs.b_id=bc.b_id where bs.staff_id=76 and customer_id is not null) and cb.last_follow_time >-863999998580524166 and cb.customer_type in (1) and (c.tel = '18846836939' or c.id in (select c_id from c_contact where c_mobile = '18846836939' or c_workphone = '18846836939')) group by cb.customer_id order by max(cb.last_follow_time) desc


ps:条件中有last_follow_time >-863999998580524166。很明显这个数值是有问题的,这个是程序逻辑错误,可根据业务逻辑继续优化应用端



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值