这个选择MUTUAL FRIEND的查询是否正确?

时间:2012-08-06 08:37:01

标签: php mysql

<?php
    mysql_connect("localhost","root","");
    mysql_select_db('db2012');
    $uid = 8;
    $mid = 10;

    $q = mysql_query("select friend from users_friends where user = $uid") or die(mysql_error());
    if(mysql_num_rows($q) > 0)
    {

        while($r=mysql_fetch_array($q))
        {
            $qq = mysql_query("select friend from users_friends where user = $mid") or die(mysql_error());
            while($rr = mysql_fetch_array($qq))
            {
                if($r[friend]==$rr[friend])
                {
                    $friend_name_query = mysql_query("select name from users where uid = '$rr[friend]'") or die();
                    $friend_name = mysql_fetch_array($friend_name_query);
                    echo $friend_name[name];
                }
            }
        }   
    }


?>

这个查询是否有效,但是其他任何方式都可以使用较少的查询?我是初学者程序员,请告诉我是否有... ...

2 个答案:

答案 0 :(得分:0)

您应该只使用一个查询:

$query = 'SELECT u.name
    FROM users_friends f1 
      INNER JOIN users_friends f2 ON (f2.friend = f1.friend)
      INNER JOIN user u ON (u.uid = f2.friend)
    WHERE f1.user = "'. $uid. '"
      AND f2.user = "'. $mid .'"';

运行查询

$q = mysql_query($query) or die(mysql_error());

并执行while循环

while($r=mysql_fetch_array($q)){
  echo $r['name'];
}

如果您执行if(mysql_num_rows($q) > 0),则只需else语句,否则您只能使用while

答案 1 :(得分:0)

您可以尝试下面的内容,以获得用户8和10的共同朋友。

select * from
user_friends a inner join user_friends b on
a.friend=b.friend and (a.user='8' and b.user='10')

然后,U可以加入用户表以获取名称。