【问题标题】:mySQL "friends in common" querymySQL“共同朋友”查询
【发布时间】:2010-10-11 18:50:37
【问题描述】:

我正在尝试通过朋友表获得一组“普通朋友”:

然后我想从 users 表中选择 *,其中 userId 在好友集中。

朋友
.id...dom...sub
.1.....2.....1
.2.....1.....3
.3.....1.....4
.4.....1.....5
.5.....2.....4
.6.....2.....6
.7.....3.....2
.8.....3.....6
.9.....2.....3

用户
.id....fname...lname
.1.....安.....狐狸
.2.....抢劫.....史密斯
.3.....艾米.....oconnor
.4.....标记....棕色
.5.....杰克....休斯
.6.....sian....jong

从上表可以看出 ann(user_1) 是 2,3,4 和 5 的朋友...而 rob(user_2) 是 1, 3, 4 和 6 的朋友。

但是我如何编写一个查询来从两个给定用户之间的共同朋友的 usersTable 中获取 userId??

我感觉它与 UNION 有关,但欢迎任何建议......

谢谢大家

【问题讨论】:

    标签: mysql


    【解决方案1】:

    这是我想出的:

    SELECT distinct fic.* from users l
    JOIN friends fol ON (fol.dom=l.id OR fol.sub=l.id)
    JOIN users fic ON (fol.dom=fic.id OR fol.sub=fic.id)
    JOIN friends fofic ON (fofic.dom=fic.id OR fofic.sub=fic.id)
    JOIN users r ON (r.id=fofic.dom OR r.id=fofic.sub)
    WHERE r.id=1 AND l.id=2 AND fic.id NOT IN (1,2);
    

    我将表格别名为 fic = 共同朋友,fofic = 共同朋友的朋友。我从“左”用户开始,找到他的朋友,找到与“右”用户匹配的朋友。

    最后的“not in”是为了阻止我们说“amy is a friend of _ who is a friend of amy”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-15
      • 1970-01-01
      相关资源
      最近更新 更多