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
------解决方案--------------------
------解决方案--------------------
- 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