tags:

views:

60

answers:

2

have a poll table which has 10 categories and I want to view the top 5 results from highest to lowest limit into 5 categories. How can I do this in php and mysql?

here are example tables

categories

  • id
  • category_name

Votes

  • id
  • category_id
  • user_id

Users

  • id
  • username

here is my sample query:

$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";
}

I want my output to be like this from the highest votes in a categories

category1 has 30 votes
category3 has 25 votes
category5 has 23 votes
category2 has 15 votes
category4 has 10 votes
+2  A: 

Use:

$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"
}
OMG Ponies
i don't think that would work..
Ben
@OMG. That's it, critically enough.
Ben
OMG Ponies
Thanks! I have fixed it! Thank you so much!
devzone
@devzone: Glad to help, would you mind clicking the checkmark beneath the vote counter on the left side? See this link for more details: http://meta.stackoverflow.com/questions/5234/accepting-answers-what-is-it-all-about
OMG Ponies
+1  A: 

That query should do it:

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

(assuming your VOTES table primary key is "id"

Ben
I corrected a mysql error 1064 - syntax error, because you had the `GROUP BY` after the `ORDER BY`. Also, the `COUNT(v.id)` will return NULL when a category doesn't have any votes associated to it.
OMG Ponies
@OMG. I guess a right join would fix the null value issue then
Ben
@Ben: No, just need to convert the NULL to zero, using [COALESCE](http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_coalesce) (ANSI) or [IFNULL](http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_ifnull) (native MySQL)
OMG Ponies