2017-08-06 19 views
1

我有一个表的朋友,它包含以下几列: friend_id和friend_of(两者都存储唯一的用户ID) 可以说表的朋友包含以下数据:SQL提取物在同一个表中的两列独特的数据

friend_id | friend_of 
------------------------- 
    123  |  456  
    456  |  789  
    456  |  123 

因此,这意味着:
用户使用id = 123有一个朋友使用id = 456
用户使用id = 456有两个朋友使用IDS = 123(friend_1)& 789(friend_2)与
用户id = 789有一个朋友,id = 456

我想编写一个查询,给定一个用户ID显示该用户拥有的每个朋友(用他们的ID)。

例如:
如果与ID给定的用户= 123的输出将是用户的id = 456
如果与ID给定的用户= 789的输出将是用户的id = 456
如果与ID给定的用户= 456输出的用户将是ID = 123和789的用户

你能帮我解决我需要的查询吗?

回答

2
(select friend_id as all_friends from friends where friend_of=ID) 
uninon 
(select friend_of as all_friends from friends where friend_id=ID) 

我想你对只存在于其中一列的情况感兴趣。以上查询将解决这个问题。请注意,union在此处使用,而不是union all,因为需要唯一值。

+0

谢谢你,先生,真棒,这正是我需要的! – Teo

0

选择friend_id,friend_of 其中friend_id =“456”

只是改变ID来获得期望输出中

0

您可以使用查询SELECT * FROM friends WHERE friend_id='456',应该让所有的456的朋友然后做一个请使用外键friend_of加入您的“用户”表。

编辑:我没有意识到朋友是一种双向关系。在这种情况下,首先使用UNION,其他一些回复则会讨论它。 :)

0

只需使用union

Declare @id int = 1; 
select f.friendof from 
#YourTableName as f where f.friendId = @id 
union 
select f.friendId from 
#YourTableName as f where f.friendof = @id 
相关问题