How to show sequential number in MySQL query result

后端 未结 4 1168
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-02 17:54

I have some simple query:

SELECT foo, bar FROM table

i think you now whats the result looks like.

What I want to do is to show some

相关标签:
4条回答
  • 2020-12-02 18:02

    If somebody wants to display the row number after ordering records, something like this may work

    set @a=0; 
    select @a:=@a+1 serial_number,t.* 
    from ( SELECT foo, bar FROM tableORDER BY bar ) t
    
    0 讨论(0)
  • 2020-12-02 18:23
    select @rownum:=@rownum+1 No, foo, bar from table, (SELECT @rownum:=0) r;
    
    0 讨论(0)
  • 2020-12-02 18:26

    The order gets scrambled if you are using GROUP BY clause in your query. The work around is putting your query inside the FROM clause like this.

    SET @a:=0;
    SELECT @a:=@a+1 No, output.*
    FROM (
         SELECT foo, bar
         FROM table GROUP BY foo, bar
     ) output;
    
    0 讨论(0)
  • 2020-12-02 18:26

    Neither of the answers worked for me, but based on bungdito's source, I realized you can do something easier:

    SET @a:=0;
    SELECT @a:=@a+1 No, foo, bar
    FROM table;
    

    So, first make sure SET @a:=0; runs. That will set up your variable, a. Then you can increment it in the results with @a:=@a+1. I tested this with GROUP BY, ORDER BY, even JOINS and it worked as expected.

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