0

我试图根据特定条件计算表中的行数。所以,我确实设法编写了一段可以根据需要运行的代码。

但是,有点太长了。所以我想知道是否有更简单的方法来实现它。

代码:

// Comments
$sql_total_comments = mysql_query("SELECT * FROM comments");
$sql_pending_comments = mysql_query("SELECT * FROM comments WHERE comment_status = '0'");
$sql_approved_comments = mysql_query("SELECT * FROM comments WHERE comment_status = '1'");
$sql_declined_comments = mysql_query("SELECT * FROM comments WHERE comment_status = '2'");

$total_comments_num = mysql_num_rows($sql_total_comments);
$pending_comments_num = mysql_num_rows($sql_pending_comments);
$approved_comments_num = mysql_num_rows($sql_approved_comments);
$declined_comments_num = mysql_num_rows($sql_declined_comments);
4

3 回答 3

2
SELECT comment_status, COUNT(comment_status)
  FROM comments GROUP BY comment_status;

在您的代码中,要么将总数的计数加起来,要么像其他答案一样对 COUNT(*) 运行单独的查询。

所以你的代码看起来像这样,假设你使用的是 PDO:

$sql = 'SELECT comment_status, COUNT(comment_status) AS "count" '.
  'FROM comments GROUP BY comment_status;';
$query = $db->query($sql);
$count_total = 0;
$count = array( );
while (($row = $query->fetch(PDO::FETCH_ASSOC)) !== FALSE) {
  $count_total += $row['count'];
  $count[$row['comment_status']] += $row['count'];
}
$query = null;  // Because I'm neurotic about cleaning up resources.
于 2012-07-01T04:43:59.083 回答
1

使用COUNT() DB FUNCTION 来完成这项工作。

$ret = mysql_query("SELECT COUNT(*) FROM comments");
$row = mysql_fetch_row($ret);
$total_comments_num = $row[0];
于 2012-07-01T04:31:45.393 回答
0

使用select count(*) from comments where......

于 2012-07-01T04:29:08.010 回答