读书人

优化SQL语句,该怎么处理

发布时间: 2012-05-27 05:42:30 作者: rapoo

优化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 

读书人网 >SQL Server

热点推荐