所以,我有一个相当简单的查询,它有效但很慢。
有更好的方法来优化查询吗?我应该在多列上打破LEFT JOINS吗?如何进行多次运行并使用Union ALL将它们连接在一起?
这些表中可能有500,000个ROWS,并且索引很好。 请帮忙。查询需要永远运行
SELECT
ep.Id,
ep.DisplayName,
ep.EmailAddress,
COALESCE(
gs.DisplayNameMember + ' (' + gd.DisplayName + ')',
ea.DisplayName ,
ep.TrusteeUserAccountName,
ep.Trustee
) AS Trustee
FROM
dbo.ExchangePermissions ep WITH (NOLOCK)
LEFT JOIN dbo.GroupDetail gd WITH (NOLOCK) ON (ep.Trustee = gd.[Identity] OR ep.Trustee = gd.DisplayName OR ep.TrusteeUserAccountName = gd.SamAccountName)
LEFT JOIN dbo.GroupMemberShip gs WITH (NOLOCK) ON gd.name = gs.groupname
LEFT JOIN dbo.ExchangeAccount ea WITH (NOLOCK) ON (ep.Trustee = ea.[Identity] OR ep.Trustee = ea.DisplayName OR ep.TrusteeUserAccountName = ea.SamAccountName)
WHERE
ep.OTHERID= @MyParameter
答案 0 :(得分:1)
OR
中的LEFT JOIN
根本没有帮助表现。您应该将它们分解为单独的查询并将UNION
结果合并在一起。在Vykintas的回答中,我们得到以下结论:
SELECT
ep.Id,
ep.DisplayName,
ep.EmailAddress,
COALESCE(
gs.DisplayNameMember + ' (' + gd.DisplayName + ')',
ep.TrusteeUserAccountName,
ep.Trustee
) AS Trustee
FROM
dbo.ExchangePermissions ep WITH (NOLOCK)
LEFT JOIN dbo.GroupDetail gd WITH (NOLOCK) ON ep.Trustee = gd.[Identity]
LEFT JOIN dbo.GroupMemberShip gs WITH (NOLOCK) ON gd.name = gs.groupname
WHERE
ep.OTHERID= @MyParameter
UNION
SELECT
ep.Id,
ep.DisplayName,
ep.EmailAddress,
COALESCE(
gs.DisplayNameMember + ' (' + gd.DisplayName + ')',
ep.TrusteeUserAccountName,
ep.Trustee
) AS Trustee
FROM
dbo.ExchangePermissions ep WITH (NOLOCK)
LEFT JOIN dbo.GroupDetail gd WITH (NOLOCK) ON ep.Trustee = gd.DisplayName
LEFT JOIN dbo.GroupMemberShip gs WITH (NOLOCK) ON gd.name = gs.groupname
WHERE
ep.OTHERID= @MyParameter
UNION
SELECT
ep.Id,
ep.DisplayName,
ep.EmailAddress,
COALESCE(
gs.DisplayNameMember + ' (' + gd.DisplayName + ')',
ep.TrusteeUserAccountName,
ep.Trustee
) AS Trustee
FROM
dbo.ExchangePermissions ep WITH (NOLOCK)
LEFT JOIN dbo.GroupDetail gd WITH (NOLOCK) ON ep.TrusteeUserAccountName = gd.SamAccountName
LEFT JOIN dbo.GroupMemberShip gs WITH (NOLOCK) ON gd.name = gs.groupname
WHERE
ep.OTHERID= @MyParameter