当前位置: 代码迷 >> Sql Server >> 优化SQL语句,该怎么处理
  详细解决方案

优化SQL语句,该怎么处理

热度:99   发布时间:2016-04-27 12:41:17.0
优化SQL语句
select tc.*,(select sum(studyTime) from Tb_My_Study_Course_Count_Backup where userId=1442 and courseId=tc.id) as studyCount  
from Tb_Course as tc 
where 1=1 and tc.id in (select courseId from Tb_My_Course where userId=1442) 
order by tc.id desc 


求这条语句的优化方法。
版本:MS-SQL Server 2005.

------解决方案--------------------
尽量不要用in
SQL code
select tc.*,(select sum(studyTime) from Tb_My_Study_Course_Count_Backup where userId=1442 and courseId=tc.id) as studyCount   from Tb_Course as tc  inner join Tb_My_Course as tbon tc.id=tb.courseIdwhere tb.userId=1442order by tc.id desc
------解决方案--------------------
探讨
select tc.*,(select sum(studyTime) from Tb_My_Study_Course_Count_Backup where userId=1442 and courseId=tc.id) as studyCount
from Tb_Course as tc
where 1=1 and tc.id in (select courseId from Tb_……

------解决方案--------------------
SQL code
select tc.*,sum(study.studyTime) as studyCount   from Tb_Course as tc  inner join (select courseId from Tb_My_Course where userId=1442) as tbon tc.id=tb.courseId inner join (select courseId from Tb_My_Study_Course_Count_Backup where userId=1442 ) study on study.courseId=tc.idorder by tc.id desc
------解决方案--------------------
SQL code
select tc.*,a.studyCountfrom Tb_Course as tc  join (select courseId,sum(studyTime) as studyCount  from Tb_My_Study_Course_Count_Backup where userId=1442 and courseId  in (select courseId from Tb_My_Course where userId=1442) group by courseId) aon tc.id=a.courseid
  相关解决方案