我正在尝试优化下面的查询。不幸的是,我没有权限查看查询优化计划。我的初始是为左外连接添加索引。我已经尝试创建索引和强制,但没有任何运气与正确的语法或位置。这是我正在使用的代码。
CourseHandler
答案 0 :(得分:1)
根据它试图做的事情,我认为这会很快。您应该能够复制最底部的SELECT并将表变量重命名为实际的表。如果它仍然很慢,我建议确保两个表上的ID列都有索引以及Flag。
DECLARE @edtomic_dbo_info TABLE (
ID INT,
Flag VARCHAR(20),
Status_Code VARCHAR(20),
Data_Source VARCHAR(20),
type VARCHAR(20)
)
DECLARE @edtomic_dbo_infodetail TABLE (
ID INT,
code VARCHAR(20),
Flag VARCHAR(20)
)
INSERT INTO @edtomic_dbo_info
SELECT 1 AS ID,'n' AS Flag,'hrd1' AS Status_Code,'aki' AS Data_Source,'hjak' AS type
INSERT INTO @edtomic_dbo_info
SELECT 2 AS ID,'n' AS Flag,'hrd1' AS Status_Code,'aki' AS Data_Source,'hjak' AS type
INSERT INTO @edtomic_dbo_infodetail SELECT 1 AS ID,'xxxx' AS code,'n' AS Flag
INSERT INTO @edtomic_dbo_infodetail SELECT 1 AS ID,'0452' AS code,'n' AS Flag
INSERT INTO @edtomic_dbo_infodetail SELECT 1 AS ID,'0452' AS code,'n' AS Flag
INSERT INTO @edtomic_dbo_infodetail SELECT 1 AS ID,'xxxx' AS code,'n' AS Flag
INSERT INTO @edtomic_dbo_infodetail SELECT 1 AS ID,'0021' AS code,'n' AS Flag
INSERT INTO @edtomic_dbo_infodetail SELECT 2 AS ID,'xxxx' AS code,'n' AS Flag
INSERT INTO @edtomic_dbo_infodetail SELECT 2 AS ID,'0452' AS code,'n' AS Flag
select
cc.ID,
CONVERT(BIT,sum(case when id.code = '0452' then 1 else 0 end)) as is_re,
CONVERT(BIT,sum(case when id.code = '0760' then 1 else 0 end)) as is_os,
CONVERT(BIT,sum(case when id.code = '0021' then 1 else 0 end)) as is_pac
from @edtomic_dbo_info cc
LEFT JOIN @edtomic_dbo_infodetail id ON id.id = cc.Id
AND id.Flag = 'n'
where cc.Flag = 'n' and
cc.Status_Code = 'hrd1' and
cc.Data_Source = 'aki' and
cc.type = 'hjak'
GROUP BY cc.id