I'm not too familiar with SQL queries but have noticed a significant performance decrease when running a query using Select Distinct. I'm running SQL Server 2008 R2. Below is my query:
select distinct CL.ClientID, NL.Name
from CL CL
inner join PR PR on CL.ClientID = PR.ClientID
where开发者_StackOverflow PR.WBT1 in (Select distinct WBT1
from TabFields
where custInclude = 'Y' and WBT2 = '')
and PR.WBT2 = ''
order by NL.Name
Does anyone know how to revise this query without using select distinct in order to speed up the query while returning the same results? Any help is greatly appreciated. thanks.
You only need DISTINCT because of the JOIN.
So don't use a JOIN: use EXISTS and push all tables that you don't actually SELECT from into the EXISTS clause
select CL.ClientID, CL.Name
from CL CL
WHERE EXISTS (SELECT *
FROM
PR PR
JOIN
TabFields TF ON PR.WBT1 = TF.WBT1
WHERE
PR.WBT2 = '' AND
TF.custInclude = 'Y' and TF.WBT2 = '' AND
CL.ClientID = PR.ClientID
)
order by CL.Name
You definitely don't need the second SELECT DISTINCT
. You can replace it by EXIST
:
select distinct CL.ClientID, NL.Name from CL CL
inner join PR PR on CL.ClientID = PR.ClientID
WHERE EXISTS
(SELECT 1 from TabFields where WBT1=PR.WBS1 AND custInclude = 'Y' and WBT2 = '')
and PR.WBT2 = '' order by NL.Name
And I don't see NL
in FROM /JOIN
. Did you miss it or it's supposed to be CL
?
精彩评论