0
<?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];
                }
            }
        }   
    }


?>

此查询正在工作,但还有其他方法可以使用更少的查询吗?我是初学者程序员,如果有需要请告诉我...

4

2 回答 2

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

于 2012-08-06T08:45:25.727 回答
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')

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

于 2012-08-06T08:45:32.613 回答