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

前端 未结 8 1738
轻奢々
轻奢々 2020-11-21 23:57

Is there any way I can get the actual row number from a query?

I want to be able to order a table called league_girl by a field called score; and return the username

8条回答
  •  北海茫月
    2020-11-22 00:39

    I found the original answer incredibly helpful but I also wanted to grab a certain set of rows based on the row numbers I was inserting. As such, I wrapped the entire original answer in a subquery so that I could reference the row number I was inserting.

    SELECT * FROM 
    ( 
        SELECT *, @curRow := @curRow + 1 AS "row_number"
        FROM db.tableName, (SELECT @curRow := 0) r
    ) as temp
    WHERE temp.row_number BETWEEN 1 and 10;
    

    Having a subquery in a subquery is not very efficient, so it would be worth testing whether you get a better result by having your SQL server handle this query, or fetching the entire table and having the application/web server manipulate the rows after the fact.

    Personally my SQL server isn't overly busy, so having it handle the nested subqueries was preferable.

提交回复
热议问题