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

前端 未结 8 1734
轻奢々
轻奢々 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:57

    You may want to try the following:

    SELECT  l.position, 
            l.username, 
            l.score,
            @curRow := @curRow + 1 AS row_number
    FROM    league_girl l
    JOIN    (SELECT @curRow := 0) r;
    

    The JOIN (SELECT @curRow := 0) part allows the variable initialization without requiring a separate SET command.

    Test case:

    CREATE TABLE league_girl (position int, username varchar(10), score int);
    INSERT INTO league_girl VALUES (1, 'a', 10);
    INSERT INTO league_girl VALUES (2, 'b', 25);
    INSERT INTO league_girl VALUES (3, 'c', 75);
    INSERT INTO league_girl VALUES (4, 'd', 25);
    INSERT INTO league_girl VALUES (5, 'e', 55);
    INSERT INTO league_girl VALUES (6, 'f', 80);
    INSERT INTO league_girl VALUES (7, 'g', 15);
    

    Test query:

    SELECT  l.position, 
            l.username, 
            l.score,
            @curRow := @curRow + 1 AS row_number
    FROM    league_girl l
    JOIN    (SELECT @curRow := 0) r
    WHERE   l.score > 50;
    

    Result:

    +----------+----------+-------+------------+
    | position | username | score | row_number |
    +----------+----------+-------+------------+
    |        3 | c        |    75 |          1 |
    |        5 | e        |    55 |          2 |
    |        6 | f        |    80 |          3 |
    +----------+----------+-------+------------+
    3 rows in set (0.00 sec)
    
    0 讨论(0)
  • 2020-11-22 01:02

    If you just want to know the position of one specific user after order by field score, you can simply select all row from your table where field score is higher than the current user score. And use row number returned + 1 to know which position of this current user.

    Assuming that your table is league_girl and your primary field is id, you can use this:

    SELECT count(id) + 1 as rank from league_girl where score > <your_user_score>
    
    0 讨论(0)
提交回复
热议问题