【问题标题】:Mysql query to get the row position in a tableMysql查询获取表中的行位置
【发布时间】:2013-11-18 21:49:34
【问题描述】:

我有带有 id 的表(存储用户 id)并在不同的匹配中得分。我想要一个用户的位置。

所以我试试这个sql fiddle; 在这我得到了所有的行,但我只需要 id 为 3 的用户并且它在表中的位置。

像这样:

Score  Postion
26        3

即使我尝试这样做但没有成功

  1. MySql: Find row number of specific record
  2. With MySQL, how can I generate a column containing the record index in a table?

【问题讨论】:

    标签: mysql


    【解决方案1】:

    我得到了答案:http://sqlfiddle.com/#!2/b787a/2

    select * from (
    select T.*,(@rownum := @rownum + 1) as rownum from (
    select sum(score) as S,id from mytable group by id order by S desc ) as T 
    JOIN    (SELECT @rownum := 0) r 
    ) as w where id = 3
    

    更新了 sqlfiddle 及以上查询。现在它运行良好。

    【讨论】:

      【解决方案2】:

      我认为这应该可以解决问题:

      SELECT totalScore, rownum FROM (
          SELECT id,sum(score) AS totalScore,(@rownum := @rownum + 1) AS rownum
          FROM mytable 
          JOIN (SELECT @rownum := 0) r
          group by id) result
      WHERE result.ID = 3;
      

      【讨论】:

      • 与其他答案相同。我没有发现任何区别
      • 在发布之前我没有看到其他答案 - SQL-fiddle 给我留下了深刻的印象(以前从未使用过,非常有用的工具 - 感谢您分享它!)注意到其他答案有被张贴。不过,无论如何,我确实发现了一个区别 - 此处的选择省略了 ID,因此它与您最初的问题相匹配。
      • 查询不完美,在某处丢失。更新 sql fiddle 链接:sqlfiddle.com/#!2/5ff3e/25
      【解决方案3】:

      只需添加一个 where 子句

      select x.id,x.sum,x.rownum
      from(
      select id,sum(score) as sum,(@rownum := @rownum + 1) as rownum 
      from mytable 
      JOIN    (SELECT @rownum := 0) r
      group by id
        ) x
      where id =3
      

      【讨论】:

      猜你喜欢
      • 2011-10-26
      • 2013-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-20
      • 2011-06-02
      • 2013-07-04
      • 2019-04-26
      相关资源
      最近更新 更多