我有一个朋友表,可以跟踪我的数据库中的关系 用户之间的连接是双向的。 我正在为一个可能的朋友"功能,我需要向所有朋友的朋友展示谁不是我的朋友,并通过总共普通朋友的降序对他们进行排序
结构表" FRIENDS":
user_id | friend_id
1 2
2 1
1 3
3 1
3 4
4 3
2 6
6 2
3 6
6 3
例如,user_id = 1的可能朋友,这是6和4.
我试图得到这样的东西:
user_id | Possible id | id common friends | Total common friends
(friend_id)
1 6 2 2
1 6 3 2
1 4 3 1
我该如何进行此类查询?
谢谢你
答案 0 :(得分:0)
试试这个:
SELECT f1.user_id,
f2.friend_id as "Possible id (friend_id)",
f1.friend_id as "id common friends",
f3.total as "Total common friends"
FROM friends f1
INNER JOIN friends f2 on f1.friend_id = f2.user_id and f1.user_id <> f2.friend_id
INNER JOIN (
SELECT fa.user_id,
fb.friend_id,
count(fb.friend_id) as total
FROM friends fa
INNER JOIN friends fb on fa.friend_id = fb.user_id and fa.user_id <> fb.friend_id
GROUP BY fa.user_id, fb.friend_id
) f3 on f3.user_id = f1.user_id and f3.friend_id = f2.friend_id