有条件的记录计数

时间:2012-07-01 04:27:12

标签: php count mysql-num-rows

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

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

代码:

// 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);

3 个答案:

答案 0 :(得分: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.

答案 1 :(得分:1)

使用COUNT() DB FUNCTION执行此类工作。

$ret = mysql_query("SELECT COUNT(*) FROM comments");
$row = mysql_fetch_row($ret);
$total_comments_num = $row[0];

答案 2 :(得分:0)

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