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 />';
    }
}

除了为此使用两个查询之外,没有其他办法,是吗?

4

4 回答 4

2

您现在要检索两次相同的东西,对吗?如果根据查询 1 存在某些数据,请使用查询 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 回答