我有一个查询,我需要加快速度:
SELECT
Distinct Refs.SpecialtyReferredTo
FROM ABI_RiO.dbo.vwSGReferrals Refs
LEFT JOIN ABI_RiO.dbo.vwSGAppointmentsPD Apps ON Refs.ClientID = Apps. ClientID AND Refs.ReferralNumber = Apps.ReferralNumber
LEFT OUTER JOIN ABI_RiO.SchemaSG.AmsOutcome AS AOUT ON AOUT.Code=APPs.Outcome
LEFT JOIN ABI_RiO.SchemaSG.ClientIndex CI ON Refs.ClientID = CI.ClientID
LEFT JOIN ABI_RiO.SchemaSG.GenGPPractice GP ON GP.Code = CI.AIMTCCurrentGPPractice
where Refs.DischargeReason IS NULL
AND ((Apps.ContactID = ISNULL((SELECT Max(Apps2.ContactID)
FROM ABI_RiO.dbo.vwSGReferrals Refs2
LEFT JOIN ABI_RiO.dbo.vwSGAppointmentsPD Apps2 ON Refs2.ClientID = Apps2. ClientID AND Refs2.ReferralNumber = Apps2.ReferralNumber
LEFT OUTER JOIN ABI_RiO.SchemaSG.AmsOutcome AS AOUT ON AOUT.Code=APPs2.Outcome
WHERE Refs2.ClientID = Refs.ClientID
AND Refs2.ReferralNumber = Refs.ReferralNumber
AND NationalCode=5),
(SELECT Max(Apps2.ContactID)
FROM ABI_RiO.dbo.vwSGReferrals Refs2
LEFT JOIN ABI_RiO.dbo.vwSGAppointmentsPD Apps2 ON Refs2.ClientID = Apps2. ClientID AND Refs2.ReferralNumber = Apps2.ReferralNumber
WHERE Refs2.ClientID = Refs.ClientID
AND Refs2.ReferralNumber = Refs.ReferralNumber
))) OR Apps.ContactID IS NULL)
GROUP BY GP.Code, Refs.SpecialtyReferredTo
这需要永远执行。但是,如果我拆分查询的最后一部分,代码将在几秒钟内执行。IE
SELECT
Distinct GP.Code, Refs.SpecialtyReferredTo
FROM ABI_RiO.dbo.vwSGReferrals Refs
LEFT JOIN ABI_RiO.dbo.vwSGAppointmentsPD Apps ON Refs.ClientID = Apps. ClientID AND Refs.ReferralNumber = Apps.ReferralNumber
LEFT OUTER JOIN ABI_RiO.SchemaSG.AmsOutcome AS AOUT ON AOUT.Code=APPs.Outcome
LEFT JOIN ABI_RiO.SchemaSG.ClientIndex CI ON Refs.ClientID = CI.ClientID
LEFT JOIN ABI_RiO.SchemaSG.GenGPPractice GP ON GP.Code = CI.AIMTCCurrentGPPractice
where Refs.DischargeReason IS NULL
AND ((Apps.ContactID = ((SELECT Max(Apps2.ContactID)
FROM ABI_RiO.dbo.vwSGReferrals Refs2
LEFT JOIN ABI_RiO.dbo.vwSGAppointmentsPD Apps2 ON Refs2.ClientID = Apps2. ClientID AND Refs2.ReferralNumber = Apps2.ReferralNumber
LEFT OUTER JOIN ABI_RiO.SchemaSG.AmsOutcome AS AOUT ON AOUT.Code=APPs2.Outcome
WHERE Refs2.ClientID = Refs.ClientID
AND Refs2.ReferralNumber = Refs.ReferralNumber
AND NationalCode=5))))
GROUP BY GP.Code, Refs.SpecialtyReferredTo
ORDER BY GP.Code
这意味着我的问题在于这里查询的最后一部分:
(SELECT Max(Apps2.ContactID)
FROM ABI_RiO.dbo.vwSGReferrals Refs2
LEFT JOIN ABI_RiO.dbo.vwSGAppointmentsPD Apps2 ON Refs2.ClientID = Apps2. ClientID AND Refs2.ReferralNumber = Apps2.ReferralNumber
WHERE Refs2.ClientID = Refs.ClientID
AND Refs2.ReferralNumber = Refs.ReferralNumber
))) OR Apps.ContactID IS NULL)
--GROUP BY GP.Code, Refs.SpecialtyReferredTo
--ORDER BY GP.Code
添加最后一个查询块会导致最终输出的数据扩展约 10%。
谁能帮我重新编写这个查询并解释为什么最后一部分会导致执行性能下降。干杯。
R