gpt4 book ai didi

Sql IN 子句会降低性能

转载 作者:行者123 更新时间:2023-12-01 22:37:36 25 4
gpt4 key购买 nike

我需要有关 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com