如何减少SQL查询的执行时间?

时间:2018-12-03 11:48:49

标签: sql sql-server

我正在下面的sql查询中工作:

WITH courses AS
        (
            select custom_courses.module_id, student_id, custom_courses.course_name, custom_courses.pass_level, custom_courses.cc_id, assign_date,
                0 as fromComplete, completion_date, company_id
            from student_adhoc_courses WITH (NOLOCK)
                inner join custom_courses WITH (NOLOCK) on custom_courses.cc_id = student_adhoc_courses.cc_id
            UNION all

            select custom_courses.module_id, student_id, custom_courses.course_name, custom_courses.pass_level, custom_courses.cc_id, assign_date,
                0 as fromComplete, student_courses.completion_date, company_id
            from student_courses WITH (NOLOCK)
                inner join custom_courses WITH (NOLOCK) on custom_courses.cc_id = student_courses.cc_id
                UNION all

                select custom_courses.module_id, student_id, custom_courses.course_name, custom_courses.pass_level, custom_courses.cc_id,
                    null as assign_date, 1 as fromComplete, null as completion_date, company_id
                from student_courses_completed WITH (NOLOCK)
                    inner join custom_courses on custom_courses.cc_id = student_courses_completed.cc_id
        ),


select distinct

s.student_last +', '+ s.student_first name,
s.login_id as login,
s.phone as phone,
s.email as email
from students s
where s.company_id in ('1000004')

在此查询中,使用并集所有方法 因此此查询需要更多时间(16分钟)才能执行。 这样您可以减少任何查询执行时间吗?

1 个答案:

答案 0 :(得分:-1)

Did you have all the indexes there? * student_adhoc_courses.cc_id * custom_courses.cc_id (for the code it seems is Primary key here) * student_courses.cc_id * student_courses_completed.cc_id