一个有点复杂的mysql查询

时间:2011-03-06 15:11:09

标签: php mysql

我目前正在创建一个新闻数据库网站,我似乎无法创建一个查询来选择5篇最热门的新闻文章。受此查询影响的数据库的2个表是:

  • 新闻 - 包含所有新闻项目(ID,作者,消息等)
  • 费率 - 包含新闻项目的所有评分(id,news_id,评级等)

现在我的查询应该从表中选择5个news_ids具有最高平均评分和最多投票率(所以:按AVG(评级)和COUNT(*)排序)。我首先尝试使我的查询也立即从News表中获取这些news_ids的所有信息(使用WHERE id IN( - 查询选择5个最热门的news_ids--)子句)但是返回了我的MySql版本的错误不能在WHERE IN子句子查询中使用LIMIT。

好吧,我希望你能帮我解决第一个必须选择那5个news_id的查询。我现在得到的查询(但不完全正常)是:

SELECT news_id FROM 
              (SELECT news_id, AVG(rating) AS average_r, COUNT(*) AS amt_r 
                      FROM rates 
                      GROUP BY news_id 
                      ORDER BY average_r,amt_r 
                      DESC LIMIT 5
               ) AS news_rates

或与我脚本的其余内容相符:

$get_hot_news_ids = mysql_query("SELECT news_id FROM 
        (SELECT news_id, AVG(rating) AS average_r, COUNT(*) AS amt_r 
         FROM rates 
         GROUP BY news_id 
         ORDER BY average_r,amt_r DESC LIMIT 5) AS news_rates");

    $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'];
    }
    //print_r($hot_news_ids);
    $get_hot_news = mysql_query("SELECT * FROM news 
        WHERE id IN($hot_news_ids) 
        ORDER BY FIELD(id, $hot_news_ids)");

3 个答案:

答案 0 :(得分:2)

你确定average_r和amt_r都是降序排列吗?

SELECT news_id FROM 
              (SELECT news_id, AVG(rating) AS average_r, COUNT(*) AS amt_r 
                      FROM rates 
                      GROUP BY news_id 
                      ORDER BY average_r DESC, amt_r DESC
                      LIMIT 5
               ) AS news_rates

答案 1 :(得分:0)

试试这个:

SELECT TOP 5 N.id, N.author, N.message, AVG(R.rating) AS rate, COUNT(R.news_id) AS votes
FROM       news  N
INNER JOIN rates R ON N.id = R.news_id
GROUP BY N.id, N.author, N.message
ORDER BY rate, votes

答案 2 :(得分:0)

您可以改为使用加入,这将允许limit

SELECT *
FROM news n JOIN (
    SELECT news_id, AVG(rating) AS average_r, COUNT(*) AS amt_r 
    FROM rates 
    GROUP BY news_id 
    ORDER BY average_r,amt_r DESC 
    LIMIT 5
  ) top5 ON n.news_id = top5.news_id
ORDER BY top5.average_r,top5.amt_r 

注意:您可能希望将查询更改为ORDER BY average_r DESC, amt_r DESC以获得最高评分项目,而不是最低评分。