前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >一条经典SQL语句优化实例

一条经典SQL语句优化实例

作者头像
全栈程序员站长
发布2022-07-20 09:56:36
发布2022-07-20 09:56:36
2420
举报

大家好,又见面了,我是全栈君。

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://javaforall.cn/108652.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年3月1,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档