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秒

相关推荐
一只fish8 小时前
优化器架构对比:Oracle vs PostgreSQL vs MySQL
mysql·postgresql·oracle
buyue__13 小时前
Python实现连接MySQL数据库并执行目录下的所有SQL文件,遇到错误时终止执行。
python·mysql
snow@li14 小时前
MySQL:库表设计完整规范与实战方案
数据库·mysql
Shawn Dev17 小时前
MySQL Binlog 数据误删除恢复完全指南
数据库·mysql·elasticsearch
陈卿诺语18 小时前
MySQL错误-this is incompatible with sql_mode=only_full_group_by完美解决方案
sql·mysql·adb
南城以南溫暖如初14718 小时前
社区健身小程序开发流程详解:技术选型与实施经验分享
java·经验分享·spring boot·mysql·vue·apache
凤舞飘伶18 小时前
导出数据库表结构excel
python·mysql
️学习的小王19 小时前
MySQL常用函数知识点总结
数据库·mysql·oracle
万亿少女的梦16820 小时前
基于Spring Boot、Java与MySQL的同城宠物服务系统设计与实现
java·spring boot·mysql·系统设计·协同过滤
万亿少女的梦16820 小时前
基于Spring Boot、Vue与MySQL的私人健身教练预约管理系统设计
java·spring boot·mysql·vue·预约管理