我需要找到一种更有效的方法来明确地连接来自两个表的两组数据。数据保存在两个表中,这些表都进行了碎片整理,压缩和索引。其索引也经过碎片整理和压缩。在结合之前,结果集已经受到限制。
有问题的代码示例:
Select * From (
Select A.entry_id, First_name, last_name, Mobile_Phone, Email_Address, '1' As 'ownership'
From userAddressBook As A Join collectionMapping As B On A.entry_id=B.entry_id
Where A.UserID=@UserID And B.GroupNameID=@groupidentifier
Union
Select A.entry_id, First_name, last_name, Mobile_Phone, Email_Address, '0' As 'ownership'
From userAddressBook As A Join collectionMapping As B On A.entry_id=B.entry_id
Where A.UserID<>@UserID And B.GroupNameID=@groupidentifier
) As UnionTable
Order By last_name Asc, First_name Asc, entry_id Asc
我理想地寻找可以提供相同结果的替代方法。我已经尝试了以下内容:
我知道不平衡的联盟导致了性能问题,但是在这种情况下,这个查询总是会被平衡命中。
对此事的任何帮助表示赞赏,谢谢。
答案 0 :(得分:0)
Select
A.entry_id
,First_name
,last_name
,Mobile_Phone
,Email_Address
,CASE WHEN A.UserId = @UserId THEN '1' ELSE '0' END As 'ownership'
From
userAddressBook As A
Join collectionMapping As B
On A.entry_id=B.entry_id
Where
B.GroupNameID = @groupidentifier
Order By
last_name Asc
,First_name Asc
,entry_id Asc
你有几乎完全相同的查询,使用CASE表达式并在单个查询中执行它会产生更多。