列出建议的朋友

时间:2017-02-08 11:08:16

标签: php mysql left-join inner-join

我试图获取一些建议的朋友列表,这些朋友不在我的朋友中,而是在我的朋友,朋友中。

2的状态是公认的朋友。

我的会话ID是34,我与用户3的朋友和用户3是用户16的朋友,因此用户16将显示为建议的朋友,因为用户16不是我的朋友。

朋友表

id | user 1_id | user2_id | status
----------------------------------
4       3          34        2
3       34         3         2
2       3          16        2
1       16         3         2

查询 (我尝试过的)

$user1_id=$_SESSION['id'];
$user2_id=$data['id'];
$collectmutualfriendsa = mysqli_query($mysqli,"
SELECT DISTINCT r2.user1_id
FROM
friends r
INNER JOIN friends r2
ON r.user1_id = r2.user2_id
LEFT OUTER JOIN friends r3 ON r3.user2_id = r2.user1_id AND r3.user1_id=2
WHERE r.user2_id = 2 AND r3.user1_id is null");

2 个答案:

答案 0 :(得分:0)

$user1_id = $_SESSION['id']; // 34
$user2_id = $data['id']; // 3
$query = "SELECT * FROM Friends_table WHERE user1_id = '$user2_id' AND user2_id != $user1_id;";

答案 1 :(得分:0)

好的,我尝试了一个UNION,现在让它工作了。

$collectmutualfriendsa = mysqli_query($mysqli,"
SELECT *
FROM friends
WHERE user2_id NOT IN
(
   SELECT user1_id FROM friends WHERE user2_id = '$user1_id'
   UNION 
   SELECT user2_id FROM friends WHERE user2_id = '$user1_id'
)

");