PHP / mySQL计算每个国家/地区代码的总评论数

时间:2014-06-03 15:26:35

标签: php mysql sql

我在mySQL中有三个表 - 类别,主题和评论。我正在尝试计算主题的总评论数,并按总计数对每个国家/地区代码进行分组。目前,在评论表中的comments_location中有多个国家/地区代码多次出现,其中包含不同的国家/地区代码(例如,美国,英国,CH,ETC)。但是,这些国家/地区代码可以在comments_location中多次出现。我想将comments_location分组(例如,comments_location有3个英国记录,2个美国记录等 - 而不是出现三次,我想将comments_location(由单个英国,美国,ETC)分组并显示每个国家的记录总数)。以下是尝试的示例,但它不起作用:

// should there be a FOR statement and where should it be placed?
//query comments where comment location = (US,UK,ETC.)
$sqlcomment = mysql_query("SELECT * FROM comments WHERE comments_location='NEED TO RUN THROUGH EACH COUNTRY CODE AND GROUP e.g. (GROUP US - run count, then GROUP UK - run count, ETC)'");
//get comment total (run count)
$commentnumber = mysql_num_rows($sqlcomment);
//echo each variable into a string one by one (should the FOR be placed here?)
$variable1 = "CODE: NEED VARIABLE FOR COMMENTS_LOCATION, value: $commentnumber, ";
echo $variable1;

理想情况下,echo $ variable1应显示CODE:US,值:2240,CODE:UK,值:6240,CODE:CH,值:3240等继续循环,直到列出所有可能的国家/地区代码。

我是否需要存储所有可能的国家/地区代码的数组,并将它们放在$ sqlcomment的WHERE comments_location中?

1 个答案:

答案 0 :(得分:3)

请尝试以下查询:

$sqlcomment = mysql_query("SELECT comments_location,count(comments_id)as count FROM comments GROUP BY comments_location");
echo'<pre>';
while($row=mysql_fetch_array($sqlcomment)){
   print_r($row);
}
echo'</pre>';

comments_id是一个猜测,在需要时进行调整。

这应该为您提供 n 结果,而n =国家/地区的数量。您将获得每行然后是Country + the Count。

相关问题