【问题标题】:how to sort data and then number the rows in mysql? [duplicate]如何对数据进行排序,然后对mysql中的行进行编号? [复制]
【发布时间】:2015-06-27 05:05:08
【问题描述】:

有行的表,例如:

+----+
|num |
+----+
| 6  |   
| 10 |
| 3  |
+----+

我尝试降序排序,然后对行进行编号

select num, @c:=@c+1 as c from table1 order by num desc;

但这并不是我所需要的。有没有可能得到下表?

+----+----+
|num |  c |
+----+----+
| 10 |  1 |
| 6  |  2 |
| 3  |  3 |
+----+----+

【问题讨论】:

  • 当您使用num 对数据进行排序并且没有具有相同num 的其他值时,使用行号排序将没有任何区别。

标签: mysql


【解决方案1】:

试试这个:

SET @rownum:=0;

SELECT *
FROM (SELECT @rownum:=@rownum+1 as rownum, num
             *
      FROM (Select num from table1 order by num desc))

【讨论】:

    【解决方案2】:

    见:With MySQL, how can I generate a column containing the record index in a table?

    你必须初始化行数变量:

    SELECT num, @c := @c + 1 AS row_number FROM test_table JOIN (SELECT @c := 0) c ORDER BY num DESC;
    

    测试集:

    CREATE TABLE `test_table` (
      `num` int(11) NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    
    INSERT INTO `test` (`num`) VALUES (6), (10), (3);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-17
      • 1970-01-01
      相关资源
      最近更新 更多