博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
一段sql的优化
阅读量:5354 次
发布时间:2019-06-15

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

优化前代码

select *,ROW_NUMBER() OVER(order by WrongCount desc) as rowIdfrom(select Quba_IDint,Quba_Number,                      (select top 1 Sqre_AddDateTime             from tbStudentStudyQuestionRecords where Sqre_QubaId=Quba_IDint and Sqre_StudentId=200              and sqre_AnswerJudge='wrong' order by Sqre_AddDateTime desc) as Sqre_AddDateTime,           (select top 1 Sqre_StudyFromType             from tbStudentStudyQuestionRecords where Sqre_QubaId=Quba_IDint and Sqre_StudentId=200              and sqre_AnswerJudge='wrong' order by Sqre_AddDateTime desc) as Sqre_StudyFromType,				COUNT(Quba_IDint) as WrongCount				,COUNT(distinct Expo_KnowPointIDint) as KnpoCount           ,           (select top 1 Sqre_MainId              from tbStudentStudyQuestionRecords where Sqre_QubaId=Quba_IDint and Sqre_StudentId=200 and sqre_AnswerJudge='wrong'              order by Sqre_AddDateTime desc) as Sqre_MainId     from tbStudentStudyQuestionRecords     left join tbQuestionBank on Sqre_QubaId=Quba_IDint     left join tbQuestionType on QuTy_Id=Quba_Type     left join tbExamKnowPoint on Expo_ExamIDint=Quba_IDint     where Sqre_StudentId=200 and Quba_SubjectId=15 and Sqre_AnswerJudge='wrong' and QuTy_Name<>'综合题'     group by Quba_IDint,Quba_Number)as t order by quba_idint

  

优化后代码

select t.*,Sqre_AddDateTime,Sqre_StudyFromType,Sqre_MainId,Sqre_QubaId,	ROW_NUMBER() OVER(order by WrongCount desc) as rowId      from (select Quba_IDint,Quba_Number,QuTy_Name,					COUNT(Quba_IDint) as WrongCount				,COUNT(distinct Expo_KnowPointIDint) as KnpoCount,max(Sqre_Id) as lastId              from tbStudentStudyQuestionRecords              left join tbQuestionBank on Sqre_QubaId=Quba_IDint			 left join tbQuestionType on QuTy_Id=Quba_Type			 left join tbExamKnowPoint on Expo_ExamIDint=Quba_IDint             where Sqre_StudentId=200 and sqre_AnswerJudge='wrong' and Quba_SubjectId=15 and QuTy_Name<>'综合题'             group by Quba_IDint,Quba_Number,QuTy_Name) as t              left join tbStudentStudyQuestionRecords on t.lastId=Sqre_Id

 

而已看到优化后执行时间不用1秒 

优化思路,第一个sql因为有三个其实查的都是同一条语句,但是因为子查询不能查三列,之前就是这样写的。

所以想着用左连接来优化,先取出一部分,再取出一部分然后连接。

转载于:https://www.cnblogs.com/encore620/p/4270387.html

你可能感兴趣的文章
VTKMY 3.3 VS 2010 Configuration 配置
查看>>
01_1_准备ibatis环境
查看>>
windows中修改catalina.sh上传到linux执行报错This file is needed to run this program解决
查看>>
JavaScript中的BOM和DOM
查看>>
360浏览器兼容模式 不能$.post (不是a 连接 onclick的问题!!)
查看>>
spring注入Properties
查看>>
jmeter(五)创建web测试计划
查看>>
python基本数据类型
查看>>
1305: [CQOI2009]dance跳舞 - BZOJ
查看>>
将html代码中的大写标签转换成小写标签
查看>>
jmeter多线程组间的参数传递
查看>>
零散笔记
查看>>
MaiN
查看>>
[Python学习] 简单网络爬虫抓取博客文章及思想介绍
查看>>
触发器课程SQL Server 知识梳理九 触发器的使用
查看>>
信息浏览器从Android的浏览器中传递cookie数据到App中信息浏览器
查看>>
客户端连接linux虚拟机集群报错
查看>>
linux下部署一个JavaEE项目的简单步骤
查看>>
hash储存机制
查看>>
[Android学习系列16]Android把php输出的json加载到listview
查看>>