MySQL从特定行ID获得排名

时间:2016-06-29 15:38:36

标签: mysql

我有医院名单,根据已经计算的平均评分。现在我想根据以下查询的平均评分来计算医院名单的排名

SELECT    name,
          hospitalID,
          currentAvgRating,
          @curRank := @curRank + 1 AS rank
FROM      hospitals h, (SELECT @curRank := 0) r
ORDER BY  currentAvgRating DESC

现在上面的查询工作时,我想从表中查看所有医院,但是当我应用下面的WHERE子句时,结果是错误的,因为这需要行位置。

SELECT    name,
          hospitalID,
          currentAvgRating,
          @curRank := @curRank + 1 AS rank
FROM      hospitals h, (SELECT @curRank := 0) r where hospitalID = '453085'
ORDER BY  currentAvgRating DESC

当我们应用where子句时,有没有办法得到正确的结果?

2 个答案:

答案 0 :(得分:2)

如果你继续你刚发现的东西,逻辑上("当只有一个listitem,它不能被订购") - 你会得出你需要选择所有行的结论。但是没有错,你可以将它们打包成一个子选择(这甚至不是一个昂贵的选择)并将WHERE应用于:

SELECT * FROM (
  SELECT    name,
            hospitalID,
            currentAvgRating,
            @curRank := @curRank + 1 AS rank
  FROM      hospitals h, (SELECT @curRank := 0) r
  ORDER BY  currentAvgRating DESC
) toplist
WHERE toplist.hospitalID = 453085

答案 1 :(得分:1)

包装子查询。

SELECT * FROM (
    SELECT    name,
              hospitalID,
              currentAvgRating,
              @curRank := @curRank + 1 AS rank
    FROM      hospitals h, (SELECT @curRank := 0) r
    ORDER BY  currentAvgRating DESC
)
WHERE hospitalID = '453085'