在 LEFT JOIN 中获取共同好友的数量

Get number of mutual friends in LEFT JOIN

我有两个 table:

用户:

id | user | fname | sname | photo
1  | Igor | Igor  | Souza | profile.jpg
2  | John | John  | Jhow  | pic.png
3  | Lucas| Lucas | Coll  | photo.jpg

朋友:

id | friend1 | friend2 | status
1  | 1       | 3       | 2
2  | 1       | 2       | 2
3  | 3       | 2       | 2

在好友table中,status = 2表示他们是好友,friend1是发送好友请求的用户。

给select用户登录的好友,我做了($userID对应访问的用户ID个人资料页面):

SELECT u.user, u.fname, u.sname, u.photo
FROM friends f
INNER JOIN users u
ON (u.id = f.friend1 AND f.friend1 <> '$userID') OR (u.id = f.friend1 AND f.friend2 <> '$userID')
WHERE (f.friend1 = '$userID' OR f.friend2 = '$userID') AND f.status = 2

我想计算登录用户 ($userIDLog) 和访问个人资料页面的用户 ($userID) 之间的共同好友数。但我不知道该怎么做,在 LEFT JOIN 的子查询中使用 count?如果是,如何进行子查询? Obs.: 我也需要用户信息 (users)

首先假设$userId = 1 和$userIDLog = 2,现在我们可以找出登录用户的好友。

SELECT friend2 as f FROM friends where friend1 = 1 
UNION SELECT friend1 as f FROM friends WHERE friend2 =1

同理其他用户好友都是

SELECT friend2 as f FROM friends where friend1 = 2 
UNION SELECT friend1 as f FROM friends where friend2 =2 

现在如果你在 f 上加入他们,你就有了答案。

SELECT COUNT(*) FROM 
  (SELECT friend2 as f FROM friends where friend1 = 1 
   UNION SELECT friend1 as f FROM friends WHERE friend2 =1) AS a
  INNER JOIN
  (SELECT friend2 as f FROM friends where friend1 = 2 
   UNION SELECT friend1 as f FROM friends where friend2 =2 ) AS b
  ON a.f = b.f

他们唯一的共同朋友是 3,对于此查询,您得到的答案计数 = 1。