mysql - SQL逻辑: sort result by product of a column and number of colums of a specific type

标签 mysql sql sorting pdo

用户可以按评论分数对我的目录进行排序。以下是通过评论分数抓取目录的 SQL:

   SELECT *, null AS score, '0' AS SortOrder
        FROM products
        WHERE datelive < 0
   UNION
   SELECT p.*, ROUND(SUM(r.score)/COUNT(*)) AS score, '1' AS SortOrder
        FROM products p
        LEFT JOIN reviews r
            ON r.id = p.id
            AND p.datelive > 0
        GROUP BY p.id
        HAVING COUNT(*) >= 5
    UNION
    SELECT p.*, null AS score, '2' AS SortOrder
        FROM products p
        LEFT JOIN reviews r
            ON r.id = p.id
            WHERE p.datelive > 0
        GROUP BY p.id
        HAVING COUNT(*) < 5
    ORDER BY SortOrder ASC, score DESC

它的作用是按顺序获取以下内容:

  • datelive 类型的产品 < 0
  • datelive 类型的产品 > 0 且 >= 5 条评论
  • datelive 类型的产品 > 0 条评论且 < 5 条评论

整个内容也是按照评论分数排序的。我想按原样对中间的要点进行排序,但乘以分数 >= 3.53 的评论百分比。

假设某个产品的原始评论得分为 4.53,但二十条评论中有两条低于 3.53,即 90% 的评论得分 >= 3.53。我想按 (score*mult) 对其进行排序,其中 mult 是评论数 >= 3.53 除以评论总数。在本例中,我排序的分数是 4.53 * 0.9 = 4.08

最佳答案

mult 添加到中间查询,并将 1 作为其他查询中的值。然后在 ORDER BY 子句中使用 score*mult

此外,MySQL 有一个内置函数用于计算平均值,您不需要除以计数。

   SELECT *, null AS score, '0' AS SortOrder, 1 AS mult
        FROM products
        WHERE datelive < 0
   UNION
   SELECT p.*, ROUND(AVG(r.score)) AS score, '1' AS SortOrder,
            SUM(r.score > 3.53)/count(*) AS mult
        FROM products p
        LEFT JOIN reviews r
            ON r.id = p.id
            AND p.datelive > 0
        GROUP BY p.id
        HAVING COUNT(*) >= 5
    UNION
    SELECT p.*, null AS score, '2' AS SortOrder, 1 AS mult
        FROM products p
        LEFT JOIN reviews r
            ON r.id = p.id
            WHERE p.datelive > 0
        GROUP BY p.id
        HAVING COUNT(*) < 5
    ORDER BY SortOrder ASC, score*mult DESC

关于mysql - SQL逻辑: sort result by product of a column and number of colums of a specific type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34552470/

相关文章:

R:gtools混合排序的意外自然排序

regex - 如何按行长排序,然后按字母顺序反转

mysql - 在日期和有限 IP 之间进行选择

php - 数据表:根据数据库值隐藏列

mysql - Oracle DBMS 中带有 to_date 子查询的 DELETE

mysql - 在一个sql中加入2条select语句

c# - OrmLite 在连接表中选择多列

sql - 别名上的 JOIN 语句 - SQL Server

Mysql GROUP BY 查询。按日期和时间显示数据

swift - 按字母顺序排序结构(swift4)