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,导致走的是全表扫描:

如果没用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这个字符串。

执行计划走了索引:

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

相关推荐
用户8307196840821 小时前
Java 告别繁琐数据统计代码!MySQL 8 窗口函数真香
java·sql·mysql
stark张宇3 小时前
MySQL 核心内幕:从索引原理、字段选型到日志机制与外键约束,一篇打通数据库任督二脉
数据库·mysql·架构
Hoffer_1 天前
MySQL 强制索引:USE/FORCE INDEX 用法与避坑
后端·mysql
Hoffer_1 天前
MySQL 索引核心操作:CREATE/DROP/SHOW
后端·mysql
0xDevNull3 天前
MySQL索引进阶用法
后端·mysql
0xDevNull3 天前
MySQL索引用法
mysql
程序员小崔日记3 天前
一篇文章彻底搞懂 MySQL 和 Redis:原理、区别、项目用法全解析(建议收藏)
redis·mysql·项目实战
武子康3 天前
大数据-241 离线数仓 - 实战:电商核心交易数据模型与 MySQL 源表设计(订单/商品/品类/店铺/支付)
大数据·后端·mysql
用户8307196840824 天前
MySQL 查询优化 30 条封神技巧:用好索引,少耗资源,查询快到飞起
mysql
Nyarlathotep01134 天前
事务隔离级别
sql·mysql