在while循环中查询

时间:2013-05-30 19:24:12

标签: php mysqli

我有这个查询电话:

$currplayer = 1;

$query = "SELECT f.fk_user_id2, u.username, u.profileimg FROM ".$prefix."_friends f 
                        INNER JOIN ".$prefix."_users u
                            ON f.fk_user_id2 = u.id     
                    WHERE f.fk_user_id1 = $currplayer ORDER BY u.username ASC";

if ($result = $mysqli->query($query)){
    while ($row1 = $result->fetch_assoc()){

        $friendid = $row1['fk_user_id2'];

        $sql = $mysqli->query("SELECT * FROM ".$prefix."_newversus WHERE fk_player=$currplayer AND fk_opponent=$friendid");
        $row = $sql->fetch_assoc();

我试图找出如何通过内部联接将循环内的查询转换为第一个查询,但无法解决这个问题。

希望得到帮助并提前感谢: - )

1 个答案:

答案 0 :(得分:1)

如果我说得对,你想要删除循环中运行的查询;将其添加到主查询。

试试这个:

SELECT f.fk_user_id2, u.username, u.profileimg FROM ".$prefix."_friends f 
INNER JOIN ".$prefix."_users u ON f.fk_user_id2 = u.id 
INNER JOIN ".$prefix."_newversus n ON f.fk_user_id2 = n.fk_opponent 
WHERE f.fk_user_id1 = $currplayer AND
n.fk_player=$currplayer
ORDER BY u.username ASC;