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秒

相关推荐
凌寒1116 小时前
Linux(Debian)安装、卸载 MySQL
linux·运维·mysql·debian
oneslide17 小时前
分享一个MySQL数据库备份恢复脚本--II
数据库·mysql
q***239218 小时前
MySQL数据库误删恢复_mysql 数据 误删
数据库·mysql·adb
合作小小程序员小小店18 小时前
web网页开发,在线%图书管理%系统,基于Idea,html,css,jQuery,java,ssm,mysql。
java·前端·后端·mysql·jdk·intellij-idea
IUGEI18 小时前
【MySQL】SQL慢查询如何排查?从慢查询排查到最终优化完整流程
java·数据库·后端·mysql·go
合作小小程序员小小店18 小时前
web网页开发,在线%食堂管理%系统,基于Idea,html,css,jQuery,java,ssm,mysql。
java·前端·mysql·html·intellij-idea·jquery
w***48119 小时前
Springboot项目本地连接并操作MySQL数据库
数据库·spring boot·mysql
友友马19 小时前
『MySQL』 - 事务 (二)
数据库·mysql·oracle
又是忙碌的一天21 小时前
mysql 学习第二天 SQL语句
sql·学习·mysql
q***925121 小时前
MySQL 启动失败 (code=exited, status=1FAILURE) 异常解决方案
数据库·mysql