it seemed multiple solutions worked, I just figured that I should just make one subquery in the FROM clause, which selects all news_id's and corresponding averages, and then in the main query select all news_ids from that subquery and order it by the averages selected in the subquery:
mysql_query("SELECT news_id FROM (SELECT news_id AS news_id, AVG(rating) AS average FROM rates GROUP BY news_id) AS news ORDER BY average DESC LIMIT 5 ")or die(mysql_error());
Also when I tested my earlier code it seemed to work just fine as well:
mysql_query("SELECT news_id FROM (SELECT news_id AS news_id, AVG(rating) AS average FROM rates GROUP BY news_id ORDER BY average DESC LIMIT 5) AS news ")or die(mysql_error());
Thanks for the help, I think I can make it to work now :) I'll just let this be the subquery in the where clause containing all news_ids to select, e.g.:
mysql_query("SELECT * FROM news WHERE news_id IN(SELECT news_id FROM (SELECT news_id AS news_id, AVG(rating) AS average FROM rates GROUP BY news_id) AS news ORDER BY average DESC LIMIT 5 ) ")or die(mysql_error());
I guess that should do the job!
Cheers.
EDIT1: when I ran my last query, apperantly my MySql version did not support the LIMIT statement inside an IN-subquery. Not much later I realized I could just put the LIMIT part inside the main query and it would result into the same, so I did:
mysql_query("SELECT * FROM news WHERE id IN(SELECT id FROM (SELECT news_id AS id, AVG(rating) AS average FROM rates GROUP BY id) AS news_rates ORDER BY average DESC) LIMIT 5")or die(mysql_error());
EDIT2: it did not give the desired output =/... My redenation in EDIT1 was wrong ><
EDIT3: lol, I got it to work using 2 queries instead of 1 with the 2nd query as sub-query inside the WHERE IN part of the main query. Still wondering why it doens't work when I put that 2nd query as sub-query inside the WHERE-IN part. Now I first executed the sub-query that selects all IDs, and then made 2nd query which selects the news with those ids. But I'm sure this could be done in one query ( also with my MySql version ). But anyway, this is my code now:
$get_hot_news_ids = mysql_query("SELECT news_id FROM (SELECT news_id AS news_id, AVG(rating) AS average FROM rates GROUP BY news_id) AS news ORDER BY average DESC LIMIT 5 ");
$first = 1;
while($news_id = mysql_fetch_assoc($get_hot_news_ids)) {
if(!$first) {
$hot_news_ids .= " ,";
}else{
$first = 0;
}
$hot_news_ids .= $news_id['news_id'];
}
$get_hot_news = mysql_query("SELECT * FROM news WHERE id IN($hot_news_ids) ORDER BY FIELD(id, $hot_news_ids)");
fixed the order of the selection
Edited by webcodez, 06 March 2011 - 06:11 AM.