在while循环中查询是否可以?

时间:2012-12-04 12:36:08

标签: php mysql

我在一个数据库中有两个表。我查询第一个表限制10然后循环结果。在while循环中,我再次使用第一个查询中的数据作为参数进行另一个查询。以下是该脚本的示例:

<?php

    $con = mysql_connect(host,username,password);
    mysql_select_db(game_server);

    //My first query
    $q1 = mysql_query('SELECT * FROM game_characters ORDER BY score DESC LIMIT 10');

    while($character = mysql_fetch_object($q1)){
    //My second query
        $q2 = mysql_query('SELECT * FROM game_board WHERE id="'.$character->id.'"');
        $player = mysql_fetch_object($q2);
    }
?>

因此,如果我有100行的结果,那么第二个查询将执行100次。我知道这不好。我怎样才能做得更好有没有办法在一个查询中执行所有操作?如果在while循环中有另一个查询,其中使用第二个查询中的数据作为参数怎么办?

  

P.S。:我正在为在线游戏做排名系统。

4 个答案:

答案 0 :(得分:3)

如果使用JOIN,则可以在一个查询中执行此操作。

SELECT * FROM game_board AS b 
    LEFT JOIN game_characters AS c ON b.id = c.id 
ORDER BY c.score DESC 
LIMIT 10

您还可以使用嵌套查询

SELECT * FROM game_board AS b WHERE 
  id IN (SELECT id FROM game_characters AS c ORDER BY score DESC LIMIT 10)

您还可以将所有game_character.id放入数组中,然后使用

$sql = "SELECT * FROM game_board AS b WHERE b.id IN (" . implode(', ', $game_character_ids) . ")";

答案 1 :(得分:2)

这里更好的方法是以“id1”,“id2”,“id3”等形式收集串联字符串str中的所有ID,并使用: 从game_board中选择*,其中id为(str)

答案 2 :(得分:1)

为什么不使用JOIN

这样,while循环中就不会有任何疑问:

$con = mysql_connect(host,username,password);
mysql_select_db(game_server);

//My first query
$q1 = mysql_query('
    SELECT * 
    FROM game_characters gc 
    LEFT JOIN game_board gb ON gc.id = gb.id
    ORDER BY score DESC 
    LIMIT 10
');

while($character = mysql_fetch_object($q1)){
    // do Your stuff here, no other query...

}

答案 3 :(得分:-1)

如果您执行以下操作,那该怎么办:

<?php

    $con = mysql_connect(host,username,password);
    mysql_select_db(game_server);

    //My first query
    $q1 = mysql_query('SELECT * FROM game_characters ORDER BY score DESC LIMIT 10');

    while($character = mysql_fetch_object($q1)){
    //My second query
        $characters .= " ' $character->id ' ,"
    }
    $q2 = mysql_query("SELECT * FROM game_board WHERE id in (substr($characters,0,strlen($characters - 2))");
    $player = mysql_fetch_object($q2);
?>