【发布时间】:2018-12-03 11:48:48
【问题描述】:
我已经在下面的 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')
在此查询中使用 union all 方法 所以这个查询需要更多时间(16分钟)才能执行。 那么您能否请任何人减少查询执行时间。
【问题讨论】:
-
恐怕这是无法回答的。您需要进行自己的性能测试。去看看执行计划,看看哪个部分慢。你没有给我们那个,甚至没有给我们表结构、索引等。
-
停止使用 nolock 提示 - 它不是一个神奇的“加速器”,它具有您需要了解的含义。正如发布的那样,您的查询没有使用您的 cte,因此删除它。从名为“students”的表中选择行时,distinct 的使用是可疑的 - 不是每一行都是特定学生的唯一实例吗?
-
我的建议是立即将每个部分插入临时表(如果必须,索引临时表)。然后使用 CTE 来构建您现在正在做的逻辑,最后,当您使用它时,将 Union All 替换为 Union,因为您现在使用临时表进行游戏。
标签: sql sql-server