0
UserRelations{UserID, FriendID, RelationStatus}

そして、IDが1、2、3などのユーザーがいます。ユーザー1はユーザー2にリクエストを送信しますユーザー3はユーザー1にリクエストを送信しますしたがって、データベースには次のものがあります。

1 | 2 | 1

3 | 1 | 1

今、クエリを書くのに少し混乱しています(おそらく設計が間違っています)。
ユーザーIDに基づいてすべての友達のリストを取得する必要があります。ただし、ユーザーが関係を要求した場合、または誰かが関係を要求した場合、ユーザーはそれに基づいて 2 つの列に入ることができます。
このクエリを使用すると、私から関係をリクエストしたすべてのユーザーを取得しますが、関係リクエストを送信したユーザーのリストも取得しますが、取得したプロファイル データは私のものであり、そのユーザーからのものではありません。

select ur.*, p.FirstName, p.LastName
from userRelations ur
join Profiles p on ur.UserId = p.UserId
where ur.FriendId = @UserId or
ur.UserId = @UserId
4

2 に答える 2

2

のプロファイルへの参加が欠落していると思いますFriendId:

select ur.*, p1.FirstName, p1.LastName, p2.FirstName, p2.LastName
from userRelations ur
join Profiles p1 on ur.UserId = p1.UserId
join Profiles p2 on ur.FriendId = p2.UserId
where ur.FriendId = @UserId or ur.UserId = @UserId
于 2012-04-21T16:53:47.660 に答える
1

次のように、WHERE句でOR演算子を使用する代わりに、 UNIONクエリを使用して友達を双方向に移動させる必要があります。

select               -- Get people you friended.
  ur.UserID          -- ME (i.e. the @User)
, ur.FriendID        -- The other person.
, ur.RelationStatus
, p.FirstName
, p.LastName 
from userRelations ur                    
inner join Profiles p on ur.FriendId = p.UserId
where ur.UserId = @UserId
--
union all
--
select               -- Get people who friended you.
  ur.FriendID        -- ME (i.e. the @User)
, ur.UserID          -- The other person.
, ur.RelationStatus
, p.FirstName
, p.LastName 
from userRelations ur                    
inner join Profiles p on ur.UserId = p.UserId
where ur.FriendId = @UserId 

UNIONの各半分の友情の方向性の観点を反映して、各select、joins、およびeachwhere句の列がどのように変化するかに注目してください。

于 2012-04-21T19:34:43.480 に答える