dongpao1921 2015-12-30 04:20
浏览 195
已采纳

如何构建一个SQL查询来获取用户之间的共同朋友数量?

I am busy trying to create a query that returns the number of mutual friends between users in a userlist. I have tried a few but they haven't been working as I had hoped, here is one of the queries I have tried

query("SELECT * FROM userlist WHERE userid = '$userid' AND status ='friend' AND friendid != '$userid' ");

the sql table below renders the relationships between users.

userid | friendid | type | status |
-----------------------------------
1      |2         | buddy | friend |
-----------------------------------
1      |3         | buddy | friend |
-----------------------------------
2      |3         | buddy | friend |
-----------------------------------
3      |2         | buddy | friend |
-----------------------------------
4      |2         | buddy | friend |
-----------------------------------
3      |1         | buddy | friend |
-----------------------------------
2      |4         | buddy | friend |
------------------------------------

How would I structure a query to find the number of mutual friends between userid 4 and userid 1.

Thanks.

  • 写回答

4条回答 默认 最新

  • doufei4418 2015-12-30 06:07
    关注

    I think this will help, Please note that, here i do not have used condition of "status", you can modify this query as per your requirement.

    SELECT count(*) FROM userlist as a 
    INNER JOIN  userlist as b 
    ON(b.friendid=a.friendid and  b.userid=4 and b.friendid!=1)
    WHERE a.userid=1 and b.friendid!=4
    

    This will return number of mutual friends.

    As per your data this will give result 1 as for user ID 1 and 4 there is only one mutual friend 2.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错