MySQL SELECT increment counter

后端 未结 3 780
有刺的猬
有刺的猬 2020-11-27 03:31

Here is my MySQL query:

SELECT name FROM table;

How can I also select an increment counter alongside name? Expected output:

相关标签:
3条回答
  • 2020-11-27 04:08
    select name,
          @rownum := @rownum + 1 as row_number
    from your_table
    cross join (select @rownum := 0) r
    order by name
    

    This part:

    cross join (select @rownum := 0) r
    

    makes it possible to introduce a variable without the need of a seperate query. So the first query could also be broken down into two queries like this:

    set @rownum := 0;
    
    select name,
          @rownum := @rownum + 1 as row_number
    from your_table
    order by name;
    

    for instance when used in a stored procedure.

    0 讨论(0)
  • 2020-11-27 04:17
    SELECT name,
          @rownum := @rownum + 1 as row_number
    FROM your_table
       ,
       (select @rownum := 0) r
    

    I prefer using a comma instead of CROSS JOIN as it performs faster. Using CROSS JOIN will add one extra step of adding a column to your table.

    0 讨论(0)
  • 2020-11-27 04:23

    In MySQL 8 and above you can also use the ROW_NUMBER() Window function.

    SELECT
        name,
        ROW_NUMBER() OVER ()
    FROM table
    

    Result:

    Jay  1
    roy  2
    ravi 3
    ram  4
    

    As shown by juergen d, it would be a good idea to put an ORDER BY to have a deterministic query.

    The ORDER BY can apply to the query and the counter independently. So:

    SELECT
        name,
        ROW_NUMBER() OVER (ORDER BY name DESC)
    FROM table
    ORDER BY name
    

    would give you a counter in decreasing order.

    Result:

    Jay  4
    ram  3
    ravi 2
    roy  1
    
    0 讨论(0)
提交回复
热议问题