1

我在一个数据库中有两个表。我正在查询第一个表限制 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 循环中有另一个查询,其中使用来自第二个查询的数据作为参数怎么办?

PS:我正在做一个在线游戏的排名系统。

4

4 回答 4

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) . ")";
于 2012-12-04T12:41:43.247 回答
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...

}
于 2012-12-04T12:40:05.213 回答
1

这里更好的方法是收集连接字符串 str 中的所有 ID,格式为 'id1'、'id2'、'id3',... 并使用: select * from game_board where id in (str)

于 2012-12-04T12:40:50.617 回答
-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);
?>
于 2012-12-04T12:41:30.300 回答