我有一个表(包含大约 18000 条记录的资源)和一个带有此主体的表值函数:
ALTER FUNCTION [dbo].[tfn_GetPackageResources]
(
@packageId int=null,
@resourceTypeId int=null,
@resourceCategoryId int=null,
@resourceGroupId int=null,
@resourceSubGroupId int=null
)
RETURNS TABLE
AS
RETURN
(
SELECT Resources.*
FROM Resources
INNER JOIN ResourceSubGroups ON Resources.ResourceSubGroupId=ResourceSubGroups.Id
INNER JOIN ResourceGroups ON ResourceSubGroups.ResourceGroupId=ResourceGroups.Id
INNER JOIN ResourceCategories ON ResourceGroups.ResourceCategoryId=ResourceCategories.Id
INNER JOIN ResourceTypes ON ResourceCategories.ResourceTypeId=ResourceTypes.Id
WHERE
(@resourceSubGroupId IS NULL OR ResourceSubGroupId=@resourceSubGroupId) AND
(@resourceGroupId IS NULL OR ResourceGroupId=@resourceGroupId) AND
(@resourceCategoryId IS NULL OR ResourceCategoryId=@resourceCategoryId) AND
(@resourceTypeId IS NULL OR ResourceTypeId=@resourceTypeId) AND
(@packageId IS NULL OR PackageId=@packageId)
)
现在我进行这样的查询:
SELECT id
FROM dbo.tfn_GetPackageResources(@sourcePackageId,null,null,null,null)
WHERE id not in(
SELECT a.Id
FROM dbo.tfn_GetPackageResources(@sourcePackageId,null,null,null,null) a INNER JOIN
dbo.tfn_GetPackageResources(@comparePackageId,null,null,null,null) b
ON a.No = b.No AND
a.UnitCode=b.UnitCode AND
a.IsCompound=b.IsCompound AND
a.Title=b.Title
)
这个查询大约需要 10 秒!(虽然每个部分查询运行得非常快,但整个查询都需要时间)我检查了它,LEFT JOIN
但NOT EXISTS
结果是一样的。但如果我直接在 Resources 表上运行查询,只需要一秒钟或更短的时间!快速查询是:
select * from resources where id not in (select id from resources)
我该如何解决?