我如何改进此代码,使我的代码减少数据库之旅?

时间:2010-09-08 17:26:57

标签: php mysql

我编写了一个代码,我经常绊倒数据库,这有点尴尬,我使用代码来计算评论表中的批准,待处理和垃圾邮件的数量。

这是我的代码。

 $query_approved = "SELECT COUNT(*) as approved FROM comments WHERE approve = '1'";
 $result_approved = mysql_query($query_approved);
 $row_approved = mysql_fetch_array($result_approved);
 $query_unapproved = "SELECT COUNT(*) as unapproved FROM comments WHERE approve = '0'";
 $result_unapproved = mysql_query($query_unapproved);
 $row_unapproved = mysql_fetch_array($result_unapproved);
 $query_spam = "SELECT COUNT(*) as spam FROM comments WHERE spam = '1'";
 $result_spam = mysql_query($query_spam);
 $row_spam = mysql_fetch_array($result_spam);

虽然该代码工作正常,但看起来很难看。无论如何要改善它?

4 个答案:

答案 0 :(得分:2)

使用:

SELECT SUM(CASE WHEN c.approved = '1' THEN 1 ELSE 0 END) AS cnt_approved,
       SUM(CASE WHEN c.approved = '0' THEN 1 ELSE 0 END) AS cnt_unapproved,
       SUM(CASE WHEN c.spam = '1' THEN 1 ELSE 0 END) AS cnt_spam
  FROM COMMENTS c

答案 1 :(得分:1)

你可以合并:

SELECT SUM(approve) as approved, SUM(spam) AS spam, 
    SUM(approved) - COUNT(*) as unapproved 
FROM comments

看看前三个答案(包括这个),我倾向于将凯尔西的方法视为最可持续的方法。

答案 2 :(得分:0)

您可以在一次通话中优化前两次通话

$query_approved = "SELECT COUNT(*) as totalCount , approve as status FROM comments group by approve";
 $result_approved = mysql_query($query_approved);
 $rows = mysql_fetch_array($result_approved);
foreach($rows as $row)
{
     if($row['status'] == '1')
     {
           $row_approved = $row['totalCount'];
     }
     elseif ($row['status'] == '0')
     {
           $row_unapproved = $row['totalCount'];
     }
}

 $query_spam = "SELECT COUNT(*) as spam FROM comments WHERE spam = '1'";
 $result_spam = mysql_query($query_spam);
 $row_spam = mysql_fetch_array($result_spam);

答案 3 :(得分:0)

更有效的单一查询可能是:

$SQL = "SELECT approve, spam, count(*) as cnt FROM comments GROUP BY approve, spam";
$result_approved = mysql_query($SQL );
$rows= mysql_fetch_row($result_approved);

然后,你可以预告$ rows ...

foreach ( $rows as $row ) {
   $row[0] is the approved code (1 or 0)
   $row[1] is the spam flag (1 or 0)
   $row[2] is the count for this criteria
}

你最终会得到4行,其中一行是被批准的垃圾邮件,不是垃圾邮件,未经批准是垃圾邮件而且不是垃圾邮件。