两个用户之间的共同朋友

时间:2017-09-30 13:10:50

标签: mysql

我有两张桌子

friends表: enter image description here

users表: enter image description here

并希望得到两个用户的共同朋友的名字(nom)。即: 1是2的朋友; 3是1和2的朋友。

用户1和2有共同的朋友3.我想得到他的名字' sammy'在一个查询中。

我该怎么做?

2 个答案:

答案 0 :(得分:0)

排除date_confirmation检查的逻辑,您有f1_idf2_id

SELECT f.id_des, u.nom
FROM friends f
LEFT JOIN users u ON u.id=f.id_des
WHERE 
f.id_exp=$f2_id AND
f.id_des IN (
   SELECT id_des
   FROM friends
   WHERE id_exp=$f1_id
)

这只会检查 ONE 方向。两者都邀请了同一个朋友。更复杂的部分是让另一个朋友邀请他们中的一个(圆形邀请!)

对于完整的循环答案,有4个条件。您需要在每个之间执行UNION

  1. 两人都邀请了同一个人(我给的例子)
  2. 由同一个人邀请
  3. 由F2邀请的F1邀请
  4. F2邀请了谁邀请了
  5. 除了您使用id_expid_des以及$f1_id$f2_id

    之外,所有查询都与上述查询相同

    这是第二个:

    SELECT f.id_des, u.nom
    FROM friends f
    LEFT JOIN users u ON u.id=f.id_des
    WHERE 
    f.id_exp=$f2_id AND
    f.id_des IN (
       SELECT id_des
       FROM friends
       WHERE id_exp=$f1_id
    )
    UNION DISTINCT
    SELECT f.id_des, u.nom
    FROM friends f
    LEFT JOIN users u ON u.id=f.id_des
    WHERE 
    f.id_des=$f2_id AND
    f.id_exp IN (
       SELECT id_exp
       FROM friends
       WHERE id_des=$f1_id
    )
    UNION DISTINCT
    SELECT f.id_des, u.nom
    FROM friends f
    LEFT JOIN users u ON u.id=f.id_des
    WHERE 
    f.id_des=$f2_id AND
    f.id_des IN (
       SELECT id_des
       FROM friends
       WHERE id_exp=$f1_id
    )
    UNION DISTINCT
    SELECT f.id_des, u.nom
    FROM friends f
    LEFT JOIN users u ON u.id=f.id_des
    WHERE 
    f.id_exp=$f2_id AND
    f.id_des IN (
       SELECT id_des
       FROM friends
       WHERE id_des=$f1_id
    )
    

    不容易测试,但这是概念。然后你必须消除重复: - )

答案 1 :(得分:0)

我试过这段代码:

SELECT f.id_des, u.nom FROM friends f LEFT JOIN users u ON u.id=f.id_des WHERE f.id_exp=445 AND f.id_des IN ( SELECT id_des FROM friends WHERE id_exp=400 ) UNION DISTINCT SELECT f.id_des, u.nom FROM friends f LEFT JOIN users u ON u.id=f.id_des WHERE f.id_des=445 AND f.id_exp IN ( SELECT id_exp FROM friends WHERE id_des=400 ) UNION DISTINCT SELECT f.id_des, u.nom FROM friends f LEFT JOIN users u ON u.id=f.id_des WHERE f.id_des=445 AND f.id_des IN ( SELECT id_des FROM friends WHERE id_exp=400 ) UNION DISTINCT SELECT f.id_des, u.nom FROM friends f LEFT JOIN users u ON u.id=f.id_des WHERE f.id_exp=445 AND f.id_des IN ( SELECT id_des FROM friends WHERE id_des=400 )

他告诉我:enter image description here 这是ma表朋友:enter image description here 查看朋友表的最后三行。

当我交换两个数字的位置时,它给了我另一个结果。 我认为代码不正确。 你怎么看? 感谢。