来自多行MYSQL的总评论

时间:2012-01-06 18:20:19

标签: php mysql sum

我必须通过评论对电影进行排序,所以......我尝试了一些但是我失败了。

嗯...

我有2张桌子

1 - 电影

id -- name
 1     XX
 2     YY

2 - 剧集

mid - >第一张表中的电影ID

eid - >剧集ID

id -- mid -- eid -- comments
 1     1      1       4
 2     1      2       2
 3     1      3       2
 4     2      1       1
 5     2      2       1

我尝试了

$q = mysql_query("SELECT SUM(comments) AS sum_comments, COUNT(mid) AS count_mid FROM episodes ORDER BY sum_comments DESC");
while($arr = mysql_fetch_array($q))
{
    echo $arr['count_mid']." - ".$arr['sum_comments']."<br/>";
}

Output: 5 - 10

Excepted: 1 - 8
          2 - 2

非常感谢!!

2 个答案:

答案 0 :(得分:4)

select mid,sum(comments) as TotalCommentCount from episodes 
group by mid   order by  mid

答案 1 :(得分:1)

SELECT mid,sum(comments) AS no_comment FROM episodes 
GROUP BY mid ORDER BY no_comment..