Add a numbered list column to a returned MySQL query

前端 未结 4 2090
不知归路
不知归路 2021-01-06 01:28

I am trying to get a sequential number column returned with my sql query. I need this to be inside the SELECT statement because I want to nest this query in another, and the

相关标签:
4条回答
  • 2021-01-06 01:32

    You need to use MySQL user variables. Let us take a variable t1. Initialize it at 0. And increment it in every select value.

    SET @t1=0;
    SELECT @t1 := @t1+1 as row_number, my_awesome_table.* from my_awesome_table
    

    This will do the trick.

    0 讨论(0)
  • 2021-01-06 01:35
    SELECT @rownum = @rownum + 1 AS row_number, mat.*
          FROM my_awesome_table mat, 
               (SELECT @rownum := 0) r
    
    0 讨论(0)
  • 2021-01-06 01:50

    MySQL don't do that.

    A little googling found this article:

    http://explainextended.com/2009/09/14/mysql-emulating-row_number-with-multiple-order-by-conditions/

    0 讨论(0)
  • 2021-01-06 01:51

    My favorite way to do what several other people have suggested is this:

    SELECT @rownum := (IFNULL(@rownum, 0) + 1), my_awesome_table.*
    FROM my_awesome_table
    

    You should be careful using user variables in your SELECT, though - As the docs note,

    "In SELECT @a, @a:=@a+1, ..., you might think that MySQL will evaluate @a first and then do an assignment second. However, changing the statement (for example, by adding a GROUP BY, HAVING, or ORDER BY clause) may cause MySQL to select an execution plan with a different order of evaluation."

    Different versions of MySQL may produce different results. Test accordingly, and consider numbering your rows in your code, rather than in the query.

    0 讨论(0)
提交回复
热议问题