Volkan
Volkan

Reputation: 49

SQL Select Where

i have a table like this

UserFriends
Id        UserId        RequestId       Status
1         1             2               1
2         1             3               1
3         1             4               0
4         3             2               1
5         3             4               1

basically the structure is if status is 0 request not accepted else 1 accepted and they are friends

i am trying to do get user 2 friends how can i do ?

IMPORTANT EDIT: i am trying to get user 3's friends. you know if user 1 added user 3 they are friends and user 3 added 2 and 4 they friends too (user 3 friends must return 1, 2 and 4 this is basic explanation)

Upvotes: 0

Views: 55

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521447

If I read correctly, a friendship is characterized by either a user inviting another user or by that user being invited by other users, and in both cases the request was accepted. If so, then the following UNION query should give the expected results:

SELECT RequestId
FROM UserFriends
WHERE UserId = 3 AND Status = 1
UNION
SELECT UserId
FROM UserFriends
WHERE RequestId = 3 AND Status = 1

I use a UNION here because a given user could appear as a friend more than once if a pair of users invited each other, or if an invitation were sent more than once. I am assuming that you don't want to report the same user as a friend more than once.

Output:

enter image description here

Demo here:

Rextester

Upvotes: 3

Related Questions