sql - 按共同好友数排序

标签 sql language-agnostic

我有以下表格

  • 用户(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/

相关文章:

networking - 这个哈夫曼表是如何创建的?

language-agnostic - 什么是消除尾递归?

ajax - 优雅降级 - 何时考虑

git - 如何配置 Visual Studio 代码以在保存时提交到 git?

mysql - 留言讨论查询

java - Java 虚拟机语言不可知吗?

MySQL 查询 phpmyadmin

php - 注册帐户时无法添加或更新子行

sql - 优化使用 where 子句和大量 AND/OR 的递归 postgres 查询

sql - 为什么 NVL2 在预期之外返回 NULL?