How to show GROUP BY data in a loop

MySQL table: images

id | Rating |
 1 | 3.0    |
 2 | 3.2    |
 3 | 4.7    |
 4 | 2.4    |
 5 | 2.4    |
 6 | 4.3    |
 7 | 2.4    |
 8 | 3.2    |

Basically I am trying to query the table above to get the data from these two fields (id and Rating) so that I can create the “Image of the month” page. I can query the database like this:

 $rows = @mysql_rows('SELECT ID FROM Image WHERE Live = 1 AND '.$whereDateLive.' ORDER BY Rating Desc LIMIT 15');

which gives me all image id. Then I use the foreach loop to build my list of images in descending order from the highest rating, with something like

foreach($rows as $row)
    {
    $img = new Image($row['ID'],true);
$content .= '<img src="/images/'.$img.'.jpg">';
}

This gives me a very simple list without sorting (e.g. 1st place, 2nd place, etc.). What I'm trying to do is GROUP id by rating, because, as can be seen from the table, images ID 2 and 8 have the same rating (3.2), so this will be Joint 3rd place. I can do this theoretically with the following:

 $rows = @mysql_rows('SELECT ID FROM Image WHERE Live = 1 AND '.$whereDateLive.' GROUP BY Rating ORDER BY Rating Desc LIMIT 15');

, , . foreach 1 ( ), , , . , PHP, ? - . .

, , ( ) -

Image of the Month Page Title
------------------------------
First Place
[imgid 3]
-----------
Second Place
[imgid 6]
-----------
Third Place
[imgid 2] [imgid 8]
----------
Best of the rest
(showing any image with a rating > 2.4)
+4
2

. , .

$rows = @mysql_rows
  ('select id, rating from image where live = 1 and '.$whereDateLive.' order by rating');

PHP, . :

$rating = -1;
$position = 0;

foreach($rows as $row)
{
  $img = new Image($row['id'], true);
  if(($row['rating'] = $rating) or $position > 3 then
  {
    <show the image next to the one before>
  }
  else
  {
    ++$position;
    $rating = $row['rating'];
    <show the title "n.th place" according to $position>
    <show the image>
  }
}
+2

, , - , ORDER LIMIT . (SQL Fiddle 5, ). , PHP.

SELECT aa.id, aa.rating
FROM Image AS aa
INNER JOIN (
    SELECT rating
    FROM Image
    GROUP BY rating
    ORDER BY rating DESC
    LIMIT 15
) AS _aa
ON aa.rating = _aa.rating
ORDER BY aa.rating DESC
LIMIT 15
+2

Source: https://habr.com/ru/post/1613651/


All Articles