我试图创建一个共同的朋友查询。但我不确定如何合并两个表以获得正确的结果。
因此,如果会话用户与他们的朋友有共同的朋友,那么共同的朋友就是其中之一。我正在寻找的是最好的解决方案,最快和最小的查询来完成这项工作。
用户表
id | first | last | username
----------------------------
朋友表
id | user 1_id | user2_id | status
----------------------------------
尝试查询
$collectmutualfriends = mysqli_query($mysqli,"
SELECT
user.id,
user.first,
user.last,
user.username
FROM user
LEFT JOIN friends as friends1
ON friends1.user1_id = user.id
AND friends1.user2_id = '$user2_id'
AND friends1.status = 2
LEFT JOIN friends as friends2
ON friends2.user2_id = user.id
AND friends2.user1_id = '$user2_id'
AND friends2.status = 2
GROUP BY friends2.user2_id
");
$nummutual = mysqli_num_rows($collectmutualfriends);
if($nummutual==1){
echo"<a href='mutualfriends.php?username=".$_GET['username']."'>".$nummutual." Mutual Friend<br></a>";
}else if($nummutual>1){
echo"<a href='mutualfriends.php?username=".$_GET['username']."'>".$nummutual." Mutual Friends<br></a>";
}
更新
$user1_id = $_SESSION['id'];
$user2_id = $data['id'];
$ user1_id和$ user2_id可以在friends表中的user1_id或user2_id中,具体取决于谁先发送好友请求。
答案 0 :(得分:3)
这应该可以解决问题:
$sql = "SELECT u.*
FROM friends f1
INNER JOIN friends f2 ON (f2.user2_id = f1.user2_id)
INNER JOIN user u ON (u.id = f2.user2_id)
WHERE f1.user1_id = '$user1_id'
AND f2.user1_id = '$user2_id'";