【问题标题】:Ranking Leaderboard using MYSQL Query使用 MYSQL 查询排名排行榜
【发布时间】:2020-05-26 18:29:56
【问题描述】:

我有一个问题,我的逻辑不是很好,所以我试图通过仅使用查询来做到这一点,

我有一个数据列表,我需要在其中获得他们的排名,但问题是,我需要让前两个对我高,最后两个对我低。

例如

id| name |   score
1   bob       20
2   anna      10
3   jose      30
4   boni      30
5   lea       100
6   leo       10
7   qwertina  90
8   josh      50
9   king      40
10  queen     10

假设我作为用户的 id 值为7

所以如果我登录并且我的 id 是7

我需要得到输出

id| name |   score
5   lea       100
6   leo       10
7   qwertina  90
8   josh      50
9   king      40

这在 mysql 查询中可能吗?任何帮助将不胜感激,我真的被这个问题困住了。

【问题讨论】:

    标签: php mysql database codeigniter


    【解决方案1】:

    您的逻辑似乎基于 id,这很奇怪,但我们在这里:

    SELECT id, name, score
    FROM yourTable
    WHERE id BETWEEN yourId-2 AND yourId+2
    

    【讨论】:

    • 您好,先生,感谢您的回答,我仍然想知道这个想法,请问我应该在yourID 中输入什么,如果我的 id 是 7,我将输入 BETWEEN 7-2 AND 7+2
    • 是的,当然,也可以用你的表名替换“yourTable”:)
    【解决方案2】:

    不确定只有 MySQL 的解决方案,但在伪 php 代码中

    Grab records ordered by score
    set a counter at 0
    for loop starting 0, <= count of results
      if the id your id? 
        if the loop index < 3 ? // there aren't two people ahead of you
          return rows 0 to 4
        elseif the loop index > count -3 ? // you are one of the last
          return rows count -4 to count
        else
          return rows index -2 to index + 2  // you have 2 above and below you
    

    尝试一下,如果您遇到困难,请发布您的 PHP

    【讨论】:

      猜你喜欢
      • 2018-01-31
      • 1970-01-01
      • 1970-01-01
      • 2015-01-29
      • 1970-01-01
      • 2013-04-12
      • 2016-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多