Pure-SQL Technique for Auto-Numbering Rows in Result Set

前端 未结 9 1089
误落风尘
误落风尘 2020-12-29 00:20

I\'m looking for a way to sequentially number rows in a result set (not a table). In essence, I\'m starting with a query like the following:

SELECT         


        
相关标签:
9条回答
  • 2020-12-29 00:48

    To have a meaningful row number you need to order your results. Then you can do something like this:

    SELECT id, name
        , (SELECT COUNT(*) FROM people p2 WHERE name='Spiewak' AND p2.id <= p1.id) AS RowNumber
    FROM people p1
    WHERE name = 'Spiewak'
    ORDER BY id
    

    Note that the WHERE clause of the sub query needs to match the WHERE clause or the primary key from the main query and the ORDER BY of the main query.

    SQL Server has the ROW_NUMBER() OVER construct to simplify this, but I don't know if MySQL has anything special to address it.


    Since my post here was accepted as the answer, I want to also call out Dan Goldstein's response, which is very similar in approach but uses a JOIN instead of a sub query and will often perform better

    0 讨论(0)
  • 2020-12-29 00:54

    There is no ANSI-standard way to do this of which I am aware.

    In SQL Server you have a ROW_NUMBER() function which can be used and in Oracle, there is a ROWNUM pseudo column.

    In MySQL, there is this technique

    0 讨论(0)
  • 2020-12-29 00:56

    In oracle the only database I know what you would want to do is do a sub select on the data

    i.e.

    select rownum, id , blah, blah
    from  (
    select id, name FROM people WHERE name = 'Spiewak'
    )
    

    the basic concept is that the rownum will be evaluated on the result set returned from the inner select.

    I hope this might point you to a solution that you can use.

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