计算字段值在表中的出现次数


Count the Number of Occurences a Field Value Has in a Table

我有一个值为1或0的已发布字段。我希望能够提醒用户有多少记录需要发布或未发布。我想计算表证明中published等于0的记录数,并将该值输出为

Awaiting to be published:#with published=0

我有这个,我意识到它是错误的:

$sql = mysql_query("SELECT * FROM testimonials WHERE published='0'");
$result=mysql_num_rows($sql);
echo $result;
$sql = mysql_query("SELECT SUM(published=0) AS nb_unpublished,
                           SUM(published=1) AS nb_published FROM testimonials");
$result = mysql_fetch_assoc($sql);
echo "Records awaiting to be published:" . $result['nb_unpublished'] . '<br>';
echo "Records already published:" . $result['nb_published'] . '<br>';

您可以使用这个:

SELECT SUM(IF(published='0',1,0)) AS 'count_awaiting',
  SUM(IF(published='1',1,0)) AS 'count_publish' 
FROM testimonials
#count_awaiting is number of records with published=0 
#count_publish is number of records with published=1

这是对的。你也可以找到这样的记录计数:

$sql = mysql_query("SELECT COUNT(*) AS `rows` FROM `testimonials` WHERE `published`='0'");
$result=mysql_fecth_array($sql);
echo "Awaiting to be published:".$result['rows'];