SQL连接查询结果问题

时间:2013-11-20 12:47:49

标签: sql sql-server

我有两个表,一个是Friends表,另一个表是用户配置表(所有用户相关信息,例如firstname,lastname等)都有它们之间的关系

朋友表(每个用户有两个条目,例如前两行)

enter image description here

现在我想显示上表中的用户名,如下所示

enter image description here

所以在输出中我想删除对我不起作用的重复项 我的查询

select distinct u.FirstName + ' ' + u.LastName As UserName,
      (select distinct  firstname + ' ' + lastname from UserProfiles where id =   uw.friendid) as FriendName
       from UserFriends as uw left join userprofiles as u 
       on u.id = uw.userid 

2 个答案:

答案 0 :(得分:2)

您需要在UserProfiles上加入UserFriends两次,因为有两列依赖于它。

SELECT  a.ID,
        f.FirstName + ' ' + f.LastName FriendName,
        u.FirstName + ' ' + u.LastName UserName
FROM    UserFriends a
        INNER JOIN UserProfiles f
            ON a.FriendID = f.ID
        INNER JOIN UserProfiles u
            ON a.UserID = u.ID
        INNER JOIN UserFriends dup
            ON a.FriendID = dup.UserID 
                AND dup.FriendID = a.UserID 
                AND a.ID > dup.ID

答案 1 :(得分:0)

我建议您必须使用CTE来消除重复项(可以通过自联接表来完成)。我已设法重现您的方案,因此如果您稍微调整一下查询,您将能够获得所需的结果

with cte as
(select 
t1.id as a_id
,t1.friendID as a_friendID
 ,t1.userID as a_userID
,t2.id as b_id
,t2.friendID as b_friendID
,t2.userID as b_userID
 from #temp t1
 left join #user t2 on t1.id+1=t2.id
 ),
 cte2 as

 select 
 a_id
,a_userID
,a_friendID
 from cte t1
 where a_friendID = (select b_friendID from cte t2 where t2.b_id= t1.b_id-1)
 )


select firstname+ ' '+lastname as FriendName
,firstname+ ' '+lastname as UserName 
from cte2 uw
left join   UserProfiles u on uw.a_userID=u.ID and uw.a_friendID=u.id