Mysqli排名与关系

时间:2016-03-11 20:06:10

标签: mysql

我正在努力获得有关系的分数排名 - 但不会跳过排名"SELECT * FROM $Table WHERE Score > 0 ORDER BY Score LIMIT $Count OFFSET $Offset"

我们的数据库查询的第一个版本很简单:

"SELECT UID, Name, Score, Rank, (SELECT COUNT(*) FROM $Table t2 WHERE t2.Score < t1.Score AND Score > 0) +1 AS Rank FROM $Table t1 WHERE Score > 0 ORDER BY Rank LIMIT $Count OFFSET $Offset"

然后我得到了a1ex07版本:

    // pseudo code; get user
    @RequestMapping("/users/{id}")
    public String show(Model model, @PathVariable("id") Long id) {
        User user = repository.findById(id);
        model.addAttribute("user", user);
        // the url will be /users/1
        // now do something to add ?include-posts=true
        // I can't use redirect here
        return "show";
    }

但是有空间......

我最相关的结果:

  1. documentation 解决方案有效但跳过了排名(1 - > 1 - > 3 - > 4 ...)
  2. MySQL Rank with ties 解决方案有效,但再次跳过排名
  3. MySQL Rank in the Case of Ties 排名再次跳过......
  4. Simple MySQL Update Rank with Ties 不太相关...
  5. 我希望有人可以帮助我;

      

    MySQL(i)10.1.10-MariaDB

1 个答案:

答案 0 :(得分:0)

要在mysql中实现排名,可以使用会话变量:

SELECT  tmp.UID,
        tmp.Name,
        @rnk := IF(@score = tmp.Score, @rnk, @rnk+1) AS Rank,
        @score := tmp.Score as Score
FROM    (
            SELECT      *
                FROM    $Table,
                        (SELECT @rnk := 0, @score = NULL) AS init
            ORDER BY    Score DESC
        ) AS tmp

子查询按分数对数据进行排序并初始化变量。主查询将当前行的得分与前一行的得分进行比较,确定等级

相关问题