我有以下表格
- 用户(ID、姓名、电子邮件)
- 友谊(id、user_id、friend_id)
我给出了当前用户的 user_id,我想根据共同好友的数量显示数据库中所有用户的列表。我可以毫不费力地编写一个 SQL 查询来获取两个特定对象之间的共同 friend 。我对如何在一个查询中获得所有用户的共同 friend 感到困惑。
这是获取用户 A 和用户 B 之间的共同好友的查询
SELECT users.* FROM friendships AS a
INNER JOIN friendships AS b
ON a.user_id = :a_id AND b.user_id = :b_id AND a.friend_id = b.friend_id
INNER JOIN users ON users.id = a.friend_id
有什么想法吗?
最佳答案
SELECT
users.id,
users.name,
users.email,
count(distinct facebook_friendships.user_id)
FROM users
JOIN friendships AS a ON users.id = a.friend_id
JOIN facebook_friendships AS b
ON b.user_id = a.user_id AND a.friend_id = b.friend_id
GROUP BY 1,2,3
ORDER BY 4 DESC
我不确定你的其他表的列是什么,但这个查询应该是关闭的
关于sql - 按共同好友数排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10642923/