Alternative to SELECT DISTINCT

馋奶兔 提交于 2019-12-11 03:27:35

问题


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 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.


回答1:


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



回答2:


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?



来源:https://stackoverflow.com/questions/6414550/alternative-to-select-distinct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!