Reputation: 99
I'm trying to fetch mutual friends.
I have a table structured like this:
`friends` (
`inviter` int(11) NOT NULL,
`accepter` int(11) NOT NULL,
`time` datetime NOT NULL,)
ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_turkish_ci;
My load_my_friends(##MY ID##);
query is like this:
SELECT p.id , p.name,p.lastname,p.thumb
FROM friends AS f
RIGHT JOIN profiles AS p ON ( f.accepter = p.id OR f.inviter = p.id )
WHERE f.inviter = ##MY ID##
OR f.accepter = ##MY ID##
LIMIT 0 , 5000
Could you tell me how I can fetch the mutual friends data.
Note: I'm not using any social-network script like JCOW,Social Engine etc.
Edit for @2
In the database I have user1,user2,user3,user4,user5..userX
I want a query which can fetch these results:
| id | name |lastname| thumb
1| 3 |raheel|shan | /img01.jpg
2| 7 | arqu |x | /img02.jpg
3| 8 |abcdef|hijklmno| /img06.jpg
Upvotes: 0
Views: 1254
Reputation: 1889
A query that's probably easy to understand is the following:
SELECT p.*
FROM
(
-- all friends of User A
SELECT accepter AS friend_id FROM friends WHERE inviter IN (##User_A_ID##)
UNION
SELECT inviter AS friend_id FROM friends WHERE accepter IN (##User_A_ID##)
) AS t1
-- intersect with
JOIN
(
-- all friends of User B
SELECT accepter AS friend_id FROM friends WHERE inviter IN (##User_B_ID##)
UNION
SELECT inviter AS friend_id FROM friends WHERE accepter IN (##User_B_ID##)
) AS t2
ON t1.friend_id = t2.friend_id
JOIN profiles p on p.id=t1.friend_id
Upvotes: 3
Reputation: 7505
SELECT *
FROM profiles p
WHERE p.id IN (
SELECT f_id
FROM (
SELECT accepter as f_id FROM friends where inviter IN (1,2)
UNION
SELECT inviter as f_id FROM friends where accepter IN (1,2)
) friends
GROUP BY f_id
HAVING count(*) > 1
)
assuming that friendships are unique rows....
Upvotes: 0
Reputation: 33341
Perhaps someone can come up with a much simpler way to do this, but here's my go at it:
SELECT id,name,lastname FROM profiles,
(SELECT *
FROM friends
WHERE
(inviter = 1 OR accepter = 1)
AND (accepter IN (
SELECT inviter
FROM friends
WHERE accepter = 2 AND inviter != 1)
OR accepter IN (
SELECT accepter
FROM friends
WHERE inviter = 2 AND accepter != 1)
OR inviter IN (
SELECT inviter
FROM friends
WHERE accepter = 2 AND inviter != 1)
OR inviter IN (
SELECT accepter
FROM friends
WHERE inviter = 2 AND accepter != 1)))
f
WHERE id != 1 AND (inviter = id OR accepter = id);
where user1's id = 1, and user2's id = 2
Have a look - http://sqlfiddle.com/#!2/15951/8
Upvotes: 0
Reputation: 1889
If you simply want a list of friends that are shared between two users - User_A and User_B - then this might be sufficient:
SELECT accepter
FROM friends
WHERE inviter = ##User_A_ID##
AND accepter IN (
SELECT accepter
FROM friends
WHERE inviter = ##User_B_ID## )
Join with your profiles-table to get the other related data.
Upvotes: 0