代码之家  ›  专栏  ›  技术社区  ›  Ben

MySQL选择最高等级

  •  0
  • Ben  · 技术社区  · 15 年前

    我有两列,一列叫做评分平均值,一列叫做评分计数。

    我需要选择评级最高的三行,评级计数也要考虑到等式中。

    5 回复  |  直到 8 年前
        1
  •  2
  •   Andomar    15 年前

    您可以按ORDERBY子句进行数学运算,例如:

    select    *
    from      YourTable
    order by  rating_average * rating_count DESC
    limit     3
    

    在mysql中,可以添加 limit 在查询结束时,将行集限制为前n行。

    如果您举个例子,我们可能会为您提供一个更具体的解决方案。

        2
  •  1
  •   Sven Lilienthal    15 年前
    SELECT *
    FROM table
    ORDER BY rating_average DESC,
             rating_count DESC
    LIMIT 3
    

    这将给出前3行,首先按评级平均值排序,然后按评级计数排序。

    例子:

    =================================
    | rating_average | rating_count |
    =================================
    |       9.1      |       5      |
    |       8.9      |       9      |
    |       8.9      |       3      |
    =================================
    
        3
  •  0
  •   Ian P    15 年前
    SELECT * FROM table ORDER BY rating_average DESC LIMIT 3
    

    这可能有效,但是您应该发布模式,这样我们就可以确切地看到您想要的内容。

        4
  •  0
  •   Eric Petroelje    15 年前

    您希望如何准确地考虑评分计数?如果你想限制它说出至少3个等级的项目,你可以这样做:

    SELECT rating_average, rating_count
    FROM mytable
    WHERE rating_count > 3
    ORDER BY rating_average DESC
    LIMIT 3
    
        5
  •  0
  •   David Robertson    8 年前

    如果您没有评级“平均”和评级“计数”,但您仍然希望得到Andomar给出的结果,这里是一个仅使用“产品”和“评论”表的完整查询。

    
    
        SELECT products.title,reviews.fk_productid,
        COUNT(reviews.review_id) AS review_count,
        AVG(reviews.rating) AS rating_average,
        COUNT(reviews.review_id) * AVG(reviews.rating) AS total_score 
        FROM reviews
        INNER JOIN products
        ON products.product_id = reviews.fk_productid
        GROUP BY fk_productid
        ORDER BY total_score DESC