SQL Server - 从2列获取不同的ID并存储在一个coulmn表中

时间:2018-06-12 19:38:45

标签: sql sql-server database query-optimization

我有下表

user_one    user_two
20151844    2016000
20151844    2017000
2018000     20151844
20151844    20151025
20151036    20151844

由以下查询生成

 select * from [dbo].[Contact] C
 where C.user_one=20151844 or C.user_two=20151844

我想获得以下结果,不包括当前用户ID 20151844

contact_Ids
2016000
2017000
2018000
20151025
20151036

实现它的最佳优化方法是什么?知道我想加入ids以从用户表中获取联系人姓名。

这是我的表格:

Contact 
user_one (int FK User.user_id), user_two (int FK User.user_id), status, action_user (int)

User
user_id (int PK), name , ... 

4 个答案:

答案 0 :(得分:2)

另一种选择:{{1}}

{{1}}

答案 1 :(得分:1)

使用UNIONINNER JOIN

SELECT c.[contact_Ids],
       u.[name]
       FROM (SELECT [user_one] [contact_Ids]
                    FROM [Contact]
                    WHERE [user_one] <> 20151844
                          AND [user_two] = 20151844
             UNION
             SELECT [user_two] [contact_Ids]
                    FROM [Contact]
                    WHERE [user_two] <> 20151844
                          AND [user_one] = 20151844) c
             INNER JOIN [User] u
                        ON u.[user_id] = c.[contact_Ids]
       ORDER BY c.[contact_Ids];

答案 2 :(得分:0)

使用apply

select tt.contact_Ids
from table t cross apply ( 
         values (user_one), (user_two) 
    ) tt (contact_Ids)
group by tt.contact_Ids
having count(*) = 1;

答案 3 :(得分:0)

设置操作Unionexcept效果最佳。

;with ids as (
select user_one id from contact
union
select user_two from contact
except
select 20151844
)
select u.*
from [user] u 
inner join ids on u.user_id = ids.id