如何选择共同的朋友

时间:2016-03-03 12:49:37

标签: php mysql

请我选择用户的共同朋友,$my_id$_SESSION['user'];$user_id是所选用户。这是代码:

    <?php

include 'connect.php';

include 'functions.php';

$my_frnds = mysqli_query{$con, "SELECT * FROM friends WHERE one='$my_id' OR two='$my_id'"};
while($my_friends = mysqli_fetch_array($my_frnds)){
    $one = $my_friends['one'];
    $two = $my_friends['two'];

    if($one == $my_id){
        $user == $two;
    } else
        $user == $one;
}

$user_frnds = mysqli_query{$con, "SELECT * FROM friends WHERE one='$user_id' OR two='$user_id'"};
while($user_friends = mysqli_fetch_array($user_frnds)){
    $user_one = $user_friends['one'];
    $user_two = $user_friends['two'];

    if($user_one == $my_id){
        $users == $user_two;
    } else
        $users == $user_one;
}

?>

假设我的朋友是(1,2,3,4,5,6,7),而用户朋友是(2,4,6,7,8,9,10),所以共同的朋友是( 2,4,6,7)我的问题是如何让共同的朋友出来并回应他们的ids?对不起,我犯了一个错误,这是原始编码

2 个答案:

答案 0 :(得分:1)

如果一个是你的id,两个是朋友id:

select * from friends 
inner join (select * from friends where one = $user_id) as temp on temp.two = friends.two
where friends.one = $my_id 

答案 1 :(得分:0)

    SELECT * FROM friends AS f1
    INNER JOIN 
    (SELECT * FROM friends WHERE one = $user_id OR two = $user_id) AS f2 
    ON (f1.one = f2.one OR f1.one = f2.two) 
    WHERE f1.one = $my_id OR f1.two = $my_id

希望这会有所帮助。