[英]Get number of mutual friends in LEFT JOIN
I've two tables: 我有两个桌子:
users : 用户 :
id | user | fname | sname | photo
1 | Igor | Igor | Souza | profile.jpg
2 | John | John | Jhow | pic.png
3 | Lucas| Lucas | Coll | photo.jpg
friends : 朋友 :
id | friend1 | friend2 | status
1 | 1 | 3 | 2
2 | 1 | 2 | 2
3 | 3 | 2 | 2
In friends table, status = 2
it means that they are friends and the friend1
is the user that send the friend request. 在好友表中,
status = 2
表示他们是好友,并且friend1
是发送好友请求的用户。
To select the friends of user logged, I did ( $userID
corresponds to the user ID profile page accessed): 要选择登录用户的朋友,我做了(
$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
I want to do a count of mutual friends between the user logged ( $userIDLog
) and the user of profile page accessed ( $userID
). 我想统计登录的用户(
$userIDLog
)和访问的个人资料页面的用户( $userID
)之间的共同朋友数量。 But I have no idea of how to do this, use a count
in a subquery on LEFT JOIN
? 但是我不知道如何做到这一点,在
LEFT JOIN
的子查询中使用count
? If yes, how to do the subquery? 如果是,该怎么做子查询? Obs.: I need users information too ( users )
观察员:我也需要用户信息( users )
First let's assume $userId = 1 and $userIDLog = 2, now we can find out the logged in user's friends with. 首先让我们假设$ userId = 1和$ userIDLog = 2,现在我们可以找到已登录用户的朋友。
SELECT friend2 as f FROM friends where friend1 = 1
UNION SELECT friend1 as f FROM friends WHERE friend2 =1
Similiarly the other users friends are given by 类似地,其他用户的朋友由
SELECT friend2 as f FROM friends where friend1 = 2
UNION SELECT friend1 as f FROM friends where friend2 =2
Now if you join them on f, you have your answer. 现在,如果您将他们加入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
The only friend they both have in common is 3 and you get the answer count = 1 for this query. 他们两个唯一的共同点是3,您将获得此查询的答案计数= 1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.