Hello.
I have two tables.
USER user_id password
FRIEND_LIST user_id friend_id
If user 1 is friend of user 2 then in friend_list there will be 2 records:
1 2
2 1
Thats how I'm controlling friend list.
My question is how can I create an efficient query that validates if a user is a friend of a friend.
For example user 1 has in his friend list user 2. and user 3 has in his friend list user 2. So user 2 is a common friend of both 1 and 3.
Here is how friend_list table looks like:
1 2
2 1
3 2
2 3
No I want to know if user 1 has a friend that has as friend user 3.
The pseudocode is as follows:
validate(){
valid = false
list = get all friends from user 1 and store them in 'list'.
for each friend in list {
list2 = get all friends from friend
for each friend2 in list2 {
if friend2.user_id = 3 }
valid = true
break; //stop here because we have found that 3 is a friend of a friend of 1
}
}
}
return valid
}
This is how it would look like in a programming language. Now I want to validate the same but just with an SQL query.
I tried this but I dont know if this is a good way to validate that.
select *
from friend_list fl1
inner join friend_list fl2 on fl1.user_id = fl2.user_id
inner join friend_list fl3 on fl2.friend_id = fl3.user_id
where fl1.user_id = 1 and fl3.friend_id = 3
Thanks in advance.
Thank you very much for your support. This is the first time I use this forum and helped me a lot.
I used the EXISTS code you posted like this.
SELECT EXISTS (
SELECT
*
FROM
friend_list AS users
INNER JOIN
friend_list AS friends
ON users.friend_id = friends.user_id
WHERE
users.user_id = 1
AND friends.friend_id = 3
) AS result