Jump to content

[SOLVED] Counting actual rows in addition to GROUP BY?


Edward

Recommended Posts

 

Hi,

 

I have just added a rating system to one of my client's sites, so people can rate the artist's CDs from 1 to 5. Here is an example table:

 

cd_name score

CD1 5

CD2 4

CD1 3

CD2 4

CD3 2

CD4 4

 

On the Home page I want to show some information on the highest rated CD, so I am using this code:

 

<?php

$mysql_connection_errors = connect_to_mysql();

if (empty($mysql_connection_errors)) {

$sql = 'SELECT cd_name, SUM(rating) FROM my_table GROUP BY cd_name ORDER BY SUM(rating) DESC LIMIT 1;';

$result = mysql_query($sql);

while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

$cd_name = $row['cd_name'];

$rating = $row['SUM(rating)'];

}

mysql_close();

}

?>

 

However, I need to prepare for the fact that there may be two or more CDs with the same score, so does anyone know how to also order my the number of rows returned? As far as I am aware, using GROUP BY will always return one, and won't count the number of rows it's grouping? Once I can do this, I will also order by cd_release_date so that if any have the same highest score, AND the same amount of votes (as per example table above), it will display the newest CD.

 

This has me stuck, any help wold be grrrrrrrreat!

 

Thanks,

 

Ed

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.