博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
一条经典SQL语句优化实例
阅读量:4320 次
发布时间:2019-06-06

本文共 1638 字,大约阅读时间需要 5 分钟。

 1、概述

如下SQL语句发生严重消耗资源的问题,使得OS's load average会在30以上,一条语句需要执行上百秒。

/*

PIXPatient 184176条
DomainPatient 184189条
PersonName 184189条
*/

捕获的SQL语句:

select *

from PIXPatient where PIXPatientTID

in (select distinct PIXPatientTID from DomainPatient where DomainPatientTID
in ( select DomainPatientTID from DomainPatient
  where PatientBirthday = '1994-01-09' or PatientBirthday = '1994-01-01'
  union select  DomainPatientTID from PersonName where FamilyName = '倪' or GivenName = '界'));

2、优化

a.优化前执行效率:
mysql>

select * from PIXPatient where PIXPatientTID

in (select distinct PIXPatientTID from DomainPatient where DomainPatientTID
in ( select DomainPatientTID from DomainPatient
  where PatientBirthday = '1994-01-09' or PatientBirthday = '1994-01-01'
  union select  DomainPatientTID from PersonName where FamilyName = '倪' or GivenName = '界'));

图片

b.加索引

alter table PersonName add index Index_FamilyName (FamilyName), add index Index_GivenName (GivenName);

alter table DomainPatient add index Index_PatientBirthday (PatientBirthday);
效果不明显
c.重构SQL语句(优化)
mysql>

select * from PIXPatient inner join (

    -> select distinct PIXPatientTID from DomainPatient inner join (
    -> select DomainPatientTID from DomainPatient  where PatientBirthday = '1994-01-09'
    -> union select DomainPatientTID from DomainPatient  where PatientBirthday = '1994-01-01'
    -> union select  DomainPatientTID from PersonName where FamilyName = '倪'
    -> union select  DomainPatientTID from PersonName where GivenName = '界' ) a using(DomainPatientTID) ) b using(PIXPatientTID) ;

图片

效果明显

3、结论

SQL语句中,尽量避免使用or,in关键字,因为执行效率低。
规律:
join > exists > in
union > or

转载于:https://www.cnblogs.com/DarrenChan/p/6423074.html

你可能感兴趣的文章
scrapy过滤重复数据和增量爬取
查看>>
scrapy-redis源码浅析
查看>>
tupian
查看>>
selenium定位非select下拉框的元素 ,定位不到
查看>>
用elasticsearch分析中国大学省份分布
查看>>
elasticsearch 常用查询 + 删除索引
查看>>
sops的配置过程
查看>>
prometheus+grafana监控Linux和kubernetes的例子
查看>>
kubernetes 简单 hello world nginx svc deployment
查看>>
kubenetes 的svc从ClusterPort 改为NodePort
查看>>
kube-metric在kubernetes上的部署
查看>>
kubespray 修改配置
查看>>
部署kubernetes-prometheus和用kubespray部署kubernetes后修改kubelet的
查看>>
Hbase和Hadoop的内存参数调优 + 前端控制台
查看>>
SQuirreL连接Phoenix报java.util.concurrent.TimeoutException
查看>>
开启phoenix命名空间的自动映射
查看>>
Hbase标准配置文件
查看>>
elasticsearch 7.1 401 Unauthorized
查看>>
hbase数据导出和恢复 设置双master
查看>>
prometheus 的promsql的经典例子
查看>>