SQL查询在表中查找好友

时间:2014-03-21 10:51:45

标签: sql union

我有两个表,UsersFriends。表格如下:

USERS
|  ID   |  Name   | 
|  1    |  Sam    | 
|  2    |  Harry  |         
|  3    |  Vivi   |
|  4    | sabrina |

FRIENDS
| UId   | FriendID| 
|  1    |    2    |    
|  2    |    3    |  
|  4    |    1    | 
|  5    |    4    | 
|  1    |    3    |  

我需要为Sam找到所有朋友的名字。我尝试在SQL查询中使用 Union 执行相同操作,但我无法获得所需的输出。我可以获得所需的输出吗?

2 个答案:

答案 0 :(得分:6)

declare
@answer nvarchar(max)='{'
select @answer=@answer+u1.Name+',' from USERS u
inner join FRIENDS f on f.UId=u.ID
inner join USERS u1 on u1.ID=f.FriendID
where u.ID=<what ever you want> //1 or 2 or 3 or 4

set @answer=SUBSTRING(@answer,0,len(@answer)-1)+'}'
select @answer

答案 1 :(得分:1)

select u.name from users
join friends f on users.id=f.uid
join users u on u.id=f.friendid
where users.name='Sam';