获得mysql排名产生错误的排名

时间:2017-12-15 04:57:41

标签: 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

但它返回错误的raking索引

enter image description here

查询有什么问题?

1 个答案:

答案 0 :(得分:1)

使用变量进行排名通常会在最新版本的MySQL中出现问题group by - 甚至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;