PHP MySQL获得前五名的最高成绩。

时间:2010-09-08 02:28:08

标签: php sql mysql

有一个包含10个类别的民意调查表,我想查看从最高到最低限制的前5个结果到5个类别。我怎么能在php和mysql中做到这一点?

这里是示例表

类别

  • ID
  • CATEGORY_NAME

投票

  • ID
  • CATEGORY_ID
  • USER_ID

用户

  • ID
  • 用户名

这是我的示例查询:

$q = mysql_query("SELECT * from categories");
while($data = mysql_fetch_array($q){

  $votes = mysql_query("SELECT * from votes where category_id=".$data['id']."");
  $data_vote = mysql_nuw_rows($votes);
  echo $data['category_name']."has".$data_vote."Votes";
}

我希望我的输出与类别中的最高票数相似

category1 has 30 votes
category3 has 25 votes
category5 has 23 votes
category2 has 15 votes
category4 has 10 votes

2 个答案:

答案 0 :(得分:3)

使用:

$q = mysql_query("SELECT c.category_name,
                         COALESCE(COUNT(v.category_id), 0) AS cnt
                    FROM CATEGORIES c
               LEFT JOIN VOTES v ON v.category_id = c.id 
                GROUP BY c.category_name
                ORDER BY cnt DESC
                   LIMIT 5 ");
while($data = mysql_fetch_array($q) {
  echo $data['category_name'] ." has ". $data['cnt'] ." votes"
}

答案 1 :(得分:2)

该查询应该这样做:

select c.category_name, count(v.id) as number_of_votes 
  from CATEGORIES c
left join VOTES v on v.category_id = c.id
    group by c.id
    order by number_of_votes desc
    limit 5

(假设你的VOTES表主键是“id”