What are ways to get mutual friends in a (1, 2) (2, 1) friendship scenario?

自作多情 提交于 2019-12-04 17:02:21
Joachim Isaksson

Looking at the table format from your other question, this should do what you want;

SELECT name FROM users u
JOIN friends f1
  ON u.uid = f1.uid OR u.uid = f1.fid
JOIN friends f2
  ON u.uid = f2.uid OR u.uid = f2.fid
WHERE (f1.uid=1 OR f1.fid=1) AND (f2.uid=3 OR f2.fid=3) 
  AND u.uid<>1 AND u.uid<>3;

Demo here.

Assuming you have called your table 'friends'.

This query will find common friends for users 1 and 3.

SELECT a.uid2
  FROM friends a
    INNER JOIN friends b
       ON a.uid2 = b.uid2
  WHERE a.uid1 = 1
   AND b.uid1 = 3

Don't you think it might be a bit presumptuous to make 2 rows though? Maybe uid 2 doesn't really like uid 1 ? (OTY).

Erwin Brandstetter

To find all common friends of uid 1 and uid 2:

SELECT t1.uid2
FROM   tbl t1
JOIN   tbl t2 USING (uid2)
WHERE  t1.uid1 = 1
AND    t2.uid1 = 2;

There is one special case, though: this query does not show whether 1 & 2 are friends!

BTW, your design seems a bit redundant. It should work with just one entry per friendship. (This query would have to be adapted for that, though.)

Basically this is another case of relational division. There are many different ways to skin this cat. Find quite under this related question - including performance testing and more information.


Query for updated question

Now there is only 1 row per friendship - a user can pop up in either column:

SELECT uid
FROM (
    SELECT uid2 AS uid FROM tbl WHERE uid1 = 1
    UNION ALL
    SELECT uid1        FROM tbl WHERE uid2 = 1
    ) u1
JOIN (
    SELECT uid2 AS uid FROM tbl WHERE uid1 = 2
    UNION ALL
    SELECT uid1        FROM tbl WHERE uid2 = 2
    ) u2 USING (uid)
$query="SELECT distinct(uid2) FROM `test` where uid1=$uid union select distinct(uid1) from test where uid2=$uid";
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!