Sql IN 子句会降低性能

标签 sql sql-server performance in-clause

我需要有关 sql 查询性能的帮助...

我有一个 View ,当我运行 View 时

select * 
from udv_salesAnalyze 
where _month=12 and _year=2012 

我在 2 秒内得到结果

但是当我添加另一个过滤器时
select * from udv_salesAnalyze 
where _month=12 and _year=2012 
and userRef in (1,2,5,6,9,11,12,13,14
,19,22,25,26,27,31,34,35,37,38,39,41,47,48,49,53,54,57,59,61,62
,65,66,67,68,69,70,74,77,78,79,80,83,86,87,88,90,91,92,94)  

我在 1 分 38 秒内得到了结果..

我将查询修改为
select * from udv_salesAnalyze 
where _month=12 and _year=2012 
and userRef in (select * from udf_dependedUsers(2)) 

(这里 udf_dependedUsers 是表返回的函数)我在 38 秒内得到了结果

我加入了 table retuned 函数来查看,但我再次在 38-40 秒内得到了结果......

有没有其他方法可以更快地获得结果...

我将非常感谢你能给我一个解决方案......

多谢 ...

execution plan :

这里是 udf_dependedUsers 的代码:
ALTER FUNCTION [dbo].[udfn_dependedUsers] (@userId int)
RETURNS @dependedUsers table (userRef int)
AS
BEGIN
DECLARE @ID INT
SET @ID = @userId
;WITH ret AS(SELECT userId FROM users
             WHERE  userId = @ID
             UNION ALL
             SELECT t.userId
             FROM   users t INNER JOIN ret r ON t.Manager = r.userId
             ) 
insert into @dependedUsers (userRef)
select * from ret
order by userId
RETURN 
END

最佳答案

尝试使用左连接

select * from udv_salasAnalyze  MainTable
LEFT JOIN
(select * from udf_dependedUsers(2)) SelectiveInTable --Try direct query like that you wrote in user function
ON SelectiveInTable.userRef = MainTable.userRef
where _month=12 and _year=2012 
and SelectiveInTable.userRef != null

关于Sql IN 子句会降低性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20764932/

相关文章:

sql - 如何递归解析SQL语句中的数据

使用 try..catch.. 时 SQL 事务不可提交。为什么?

actionscript-3 - AS3 try catch 重吗?

一个需要多个选择查询的SQL查询

SQL:SQL 异或

sql - SQL解决Toad中单元格顺序的解决方案

javascript - ng-options默认值需要双击选择一个值

使用内连接的 SQL 更新查询语法

mysql - Rails 3,预加载模型

python - 加快简单距离计算速度