我有大量的商店程序。我只粘贴了一小部分。
我的查询:
--declare variable and Select Statement goes here
WHERE ((v.[RoleID] IN (
SELECT [dbo].[aspnet_UsersInRoles].roleid
FROM [dbo].[aspnet_UsersInRoles]
INNER JOIN [dbo].[aspnet_Users]
ON [dbo].[aspnet_Users].userid = [dbo].[aspnet_UsersInRoles].userid
WHERE
[dbo].[aspnet_Users].username = @UserName
UNION ALL
SELECT [RoleId]
FROM dbo.aspnet_roles
WHERE loweredrolename = 'anonymous user')
OR v.username = @UserName))
查询工作正常,但需要很长时间才能执行。 WHERE
条件IN
内的条件太多了IN
。 我认为 IN
内的子查询需要时间。有没有办法优化此查询并替换WHERE
条件{{1}}内的{{1}}。或者建议我一种优化此类查询的替代方法。感谢。
答案 0 :(得分:1)
`create table #temp(roleid int); `
` insert into #temp as (sSELECT [dbo].[aspnet_UsersInRoles].roleid
FROM [dbo].[aspnet_UsersInRoles]
INNER JOIN [dbo].[aspnet_Users]
ON [dbo].[aspnet_Users].userid = [dbo].[aspnet_UsersInRoles].userid
WHERE
[dbo].[aspnet_Users].username = @UserName
UNION ALL
SELECT [RoleId]
FROM dbo.aspnet_roles
WHERE loweredrolename = 'anonymous user');`
WHERE ((v.[RoleID] IN ( select roleid from #temp);
答案 1 :(得分:0)
您可以使用IN子句的结果创建临时表并加入它。这会将问题分解为两个更简单的任务。
答案 2 :(得分:-2)
根据Orangecrush的建议
--declare variable and Select Statement goes here
WHERE EXISTS (
SELECT 1
FROM [dbo].[aspnet_UsersInRoles]
INNER JOIN [dbo].[aspnet_Users]
ON [dbo].[aspnet_Users].userid = [dbo].[aspnet_UsersInRoles].userid
WHERE
[dbo].[aspnet_Users].username = @UserName
AND [dbo].[aspnet_UsersInRoles].roleid = v.[RoleID]
UNION ALL
SELECT 1
FROM dbo.aspnet_roles
WHERE loweredrolename = 'anonymous user'
AND dbo.aspnet_roles.roleid = v.[RoleID])
OR v.username = @UserName)