我们的查询速度很慢:
select id
from task t
inner join TaskLog tl
on t.id = tl.id
where tl.PostImage =
(
select top 1 tll.PostImage
from TaskLog tll
where tll.id = t.id
)
group by t1.PostImage, t.id
看起来tl.PostImage =(子查询)导致缓慢。如何重写它以使其运行得更快?
编辑:
我以不正确的方式简化了问题。因此,解决方案对我没有帮助。这是我的实际查询:
SELECT distinct(p.Task_id), 1 as TotalReferrals
FROM Task p inner join Task_Log PL on PL.Task_ID = P.Task_ID
where (MONTH(P.CreateDate) = @Month
AND YEAR(P.CreateDate) = @Year)
and (((p.Worker like 'k3%'
and p.CreateDate < '12/6/2010')
or (p.Worker in ('k22', 'k27', 'k29')
and p.CreateDate >= '12/6/2010' and p.ModifiedDate < '12/1/2013')
or (p.Worker in ('K4A', 'K46', 'K48')
and p.CreateDate >= '12/1/2013'))
or (pl.post_image = (select top 1 pll.post_image
from Task_log pll
where pll.Task_id = p.Task_id
and pll.pre_image = 'Unknown'
and pll.changed_column_nm = 'Worker'
and (Month(pll.CreateDate) = @Month
and Year(pll.CreateDate) = @Year)
and ((pll.post_image like 'k3%'
and pll.CreateDate < '12/6/2010')
or (pll.post_image in ('k22', 'k27', 'k29')
and pll.CreateDate >= '12/6/2010' and pll.CreateDate < '12/1/2013')
or (pll.post_image in ('K4A', 'K46', 'K48')
and pll.CreateDate >= '12/1/2013'))
group by pll.post_image, pll.log_id
)
))
group by pl.post_image, p.Task_id, pl.CreateDate
答案 0 :(得分:0)
SELECT Min(T.id)
FROM Task T
INNER JOIN TaskLog TL
ON T.id = TL.id
GROUP BY TL.PostImage
答案 1 :(得分:0)
您可能会尝试删除子选择:
SELECT Distinct(P.Task_id), 1 as TotalReferrals
FROM Task P
INNER JOIN
Task_Log PL
ON PL.Task_ID = P.Task_ID
WHERE (MONTH(P.CreateDate) = @Month
AND YEAR(P.CreateDate) = @Year)
AND (((P.Worker like 'k3%'
AND P.CreateDate < '12/6/2010')
OR (P.Worker in ('k22', 'k27', 'k29')
AND P.CreateDate >= '12/6/2010' and P.ModifiedDate < '12/1/2013')
OR (P.Worker in ('K4A', 'K46', 'K48')
AND P.CreateDate >= '12/1/2013'))
OR (PL.pre_image = 'Unknown'
AND PL.changed_column_nm = 'Worker'
AND Month(PL.CreateDate) = @Month
AND Year(PL.CreateDate) = @Year
AND (PL.post_image like 'k3%'
AND PL.CreateDate < '12/6/2010')
OR (PL.post_image in ('k22', 'k27', 'k29')
AND PL.CreateDate >= '12/6/2010'
AND PL.CreateDate < '12/1/2013')
OR (PL.post_image in ('K4A', 'K46', 'K48')
AND PL.CreateDate >= '12/1/2013'))
GROUP BY PL.post_image, P.Task_id, PL.CreateDate