0

次のことを行うためのより効率的な方法はありますか?

$total_a = mysql_query("SELECT `id` FROM `table` WHERE `this` = 'that'");
$total_b = mysql_num_rows($total_a);

if(!$total_b)
{
    echo 'no results';
}
else
{
    $a = mysql_query("SELECT `id`, `time` FROM `table` WHERE `this` = 'that' ORDER BY `time` DESC");
    while($b = mysql_fetch_assoc($a))
    {
        echo $b['id'].'-'.$b['time'].'<br />';
    }
}

これに2つのクエリを使用する以外に方法はありませんか?

4

4 に答える 4

2

あなたは今、同じものを2回取得していますよね?クエリ1に従ってデータが存在する場合は、クエリ2でそのデータを再度取得して表示します。単純に2番目のクエリを使用しないのはなぜですか?

$sql = "SELECT id, time FROM table WHERE this = 'that' ORDER BY time DESC";
$res = mysql_query($sql);
if (mysql_num_rows($res)) {
  while ($b = ...) {
    ...
  }
} else {
  echo 'no results';
}
于 2010-10-05T09:16:58.687 に答える
1

次のようにクエリを再利用できるはずです。

$result = mysql_query("SELECT `id`, `time` FROM `table` WHERE `this` = 'that' ORDER BY `time` DESC");
$num_rows = mysql_num_rows($result);

if(!$num_rows)
{
    echo 'no results';
}
else
{
    while($row = mysql_fetch_assoc($result))
    {
        echo $row['id'].'-'.$row['time'].'<br />';
    }
}
于 2010-10-05T09:19:19.230 に答える
0

基本的にそれらは同じクエリですよね?!

できない理由:

$sql = "SELECT `id`, `time` FROM `table` WHERE `this` = 'that' ORDER BY `time` DESC";
$result = mysql_query($sql);

if(mysql_num_rows($result)){
    while($b = mysql_fetch_array($result))
    {
        echo $b['id'].'-'.$b['time'].'<br />';
    }
}
else{
  // no rows
}
于 2010-10-05T09:18:41.103 に答える
-1

ちょうど使用:

$a = mysql_query("SELECT `id`, `time` FROM `table` WHERE `this` = 'that' ORDER BY `time` DESC");
while($b = mysql_fetch_assoc($a))
{
    echo $b['id'].'-'.$b['time'].'<br />';
}

なぜ数えるの?

次のような場合にのみ、可能な行をカウントする必要があります

if($count){
echo "starting the stuff";
$a = mysql_query("SELECT `id`, `time` FROM `table` WHERE `this` = 'that' ORDER BY `time` DESC");
while($b = mysql_fetch_assoc($a))
{
    echo $b['id'].'-'.$b['time'].'<br />';
}
echo "ending the stuff";
}
于 2010-10-05T09:17:30.263 に答える