mysql - 在 mysql 上获取排名产生错误的排名

标签 mysql sql database

我试图根据评级百分比获得排名,因此 mysql 查询如下

select c.id , sum((r.value * 20))/ count(r1.pagetypeid)  as score, @curRank := @curRank + 1 AS rank from (SELECT @curRank := 0) cr, rating as r 
inner join rateelement as r1 on r.elementid = r1.id
inner join ratesubscription as r2 on r.subscriptionid = r2.id
inner join consultant as c on r2.consultantid = c.id
where r1.displayorder not in (6) and r2.agencyid = 38
group by  c.id order by score desc

但它返回错误的排名索引

enter image description here

查询出了什么问题?

最佳答案

使用变量进行排名通常会出现 group by 问题,甚至在最新版本的 MySQL 中也会出现 order by 问题。因此,使用子查询:

select x.*, (@curRank := @curRank + 1) AS rank
from (select c.id, sum((r.value * 20))/ count(r1.pagetypeid) as score 
      from rating r inner join
           rateelement r1
           on r.elementid = r1.id inner join
           ratesubscription r2
           on r.subscriptionid = r2.id inner join
           consultant c
           on r2.consultantid = c.id
      where r1.displayorder not in (6) and r2.agencyid = 38
      group by c.id
      order by score desc
     ) x cross join
     (SELECT @curRank := 0) cr;

关于mysql - 在 mysql 上获取排名产生错误的排名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47826021/

相关文章:

php - 我的 SQL 语法有错误? MySQLi 的麻烦

MySQL : transaction within a stored procedure

database - AWS RDS 自动备份

java - 在 hibernate 和 MySql 中通过外键链接的外部对象

sql - 限制型号选择

mysql - SQL 在我的特定查询中四舍五入到小数点后两位

带有 mysql 数据库的 C# 应用程序,日期保存为字符串

php - 在 SELECT 查询 (MySql) 中生成重复行

Mysql前3个计数值

mysql - 如何在单个 mysql select 语句中使用多个 where 子句?