Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

tsql - EXISTS in filter returning too many values

I need to write a query that uses EXISTS, rather than IN, so that it will run fast. The filter is being fed so many parameter values that EXISTS seems like the only option. The difference is between a 20+ minute query and a 5 second query.

This is the query I have:

SELECT DISTINCT d.GROUP_NAME
FROM [EMPLOYEE] e JOIN [DATA_FACT] d ON (e.KEY = d.KEY)
WHERE d.DATE BETWEEN @Start and @End
AND EXISTS
(              
    select '1234567' -- @ID
) 
AND e.Location IN (@Location)
ORDER BY d.GROUP_NAME ASC

The problem is that it is returning too many records. Based on the values I'm passing to filter on, I should get 1 row back but instead I am getting 28.

If I remove the EXISTS and add the following then I get the 1 record I need:

AND e.ID IN ('1234567')

Is there a way to fix the query to work with EXISTS so that I get the correct results?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is essentially what you want if you are going to try to use exists to filter your data_fact table by parameters in your employee table. Not sure how much it's going to improve your performance though when you throw a massive number of employee IDs at it.

SELECT 
    d.GROUP_NAME
FROM [DATA_FACT] AS d
WHERE d.DATE BETWEEN @Start and @End
AND EXISTS
(              
    select 1
    from EMPLOYEE AS e
    WHERE d.[KEY] = e.[KEY]
        AND e.[Location] IN (@Location)
        AND e.ID IN ('1234567')
)
ORDER BY d.GROUP_NAME ASC

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...