欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > mysql怎样优化count(*) from 表名 where …… or ……这种慢sql

mysql怎样优化count(*) from 表名 where …… or ……这种慢sql

2025/8/11 12:50:50 来源:https://blog.csdn.net/YABIGNSHI/article/details/142337052  浏览:    关键词:mysql怎样优化count(*) from 表名 where …… or ……这种慢sql

一 问题描述

线上发现一条类似这样的慢sql(查询时长8s):

select id,name,(select count(*) from t14 where t14.id=t15.id or t14.id2=t15.id) as cnt
from t15 ;

t14的id和id2字段上都有索引,但是因为条件里有or,导致走的是全表扫描:

0779299a7f0b487e9c17c02182ef2b9a.png

如果没用count(*),而是select 字段这种方式,那可以用union这种方式替代or,但这里是count(),则有些不同。

二 优化逻辑

将select count(*) from t14 where t14.id=t15.id or t14.id2=t15.id改为以下三种情况:

1、 t14.id=t14.id2,此时t14.id = t15.id与t14.id2=t15.id是等价的,写哪个都可以
2、 t14.id!=t14.id2时,分成两种情况:
① t14.id = t15.id
② t14.id2 = t15.id

三 改写后的sql

select id,name,
(select count(*) from t14 where t14.id=t15.id and t14.id=t14.id2) 
+
(select count(*) from t14 where t14.id=t15.id and ifnull(t14.id,'isnull')!=ifnull(t14.id2,'isnull')
)
+
(select count(*) from t14 where t14.id2=t15.id and t14.id!=t14.id2)
as cnt
from t15 

加ifnull(字段,'isnull')函数是因为发现关联字段是null时,关联不上,所以这里将这些空值转换为了isnull这个字符串。
执行计划走了索引:

0f0f3e0c818f4b6d920e196918aa46d0.png

逻辑看起来比之前复杂了,但是查询时长由8秒降到了1.2秒

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词