How to select the nth row in a SQL database table?

后端 未结 30 2583
执笔经年
执笔经年 2020-11-22 06:06

I\'m interested in learning some (ideally) database agnostic ways of selecting the nth row from a database table. It would also be interesting to see how this can b

相关标签:
30条回答
  • 2020-11-22 06:27

    SQL 2005 and above has this feature built-in. Use the ROW_NUMBER() function. It is excellent for web-pages with a << Prev and Next >> style browsing:

    Syntax:

    SELECT
        *
    FROM
        (
            SELECT
                ROW_NUMBER () OVER (ORDER BY MyColumnToOrderBy) AS RowNum,
                *
            FROM
                Table_1
        ) sub
    WHERE
        RowNum = 23
    
    0 讨论(0)
  • 2020-11-22 06:28

    But really, isn't all this really just parlor tricks for good database design in the first place? The few times I needed functionality like this it was for a simple one off query to make a quick report. For any real work, using tricks like these is inviting trouble. If selecting a particular row is needed then just have a column with a sequential value and be done with it.

    0 讨论(0)
  • 2020-11-22 06:29

    1 small change: n-1 instead of n.

    select *
    from thetable
    limit n-1, 1
    
    0 讨论(0)
  • 2020-11-22 06:31

    Oracle:

    select * from (select foo from bar order by foo) where ROWNUM = x
    
    0 讨论(0)
  • 2020-11-22 06:32

    When we used to work in MSSQL 2000, we did what we called the "triple-flip":

    EDITED

    DECLARE @InnerPageSize int
    DECLARE @OuterPageSize int
    DECLARE @Count int
    
    SELECT @Count = COUNT(<column>) FROM <TABLE>
    SET @InnerPageSize = @PageNum * @PageSize
    SET @OuterPageSize = @Count - ((@PageNum - 1) * @PageSize)
    
    IF (@OuterPageSize < 0)
        SET @OuterPageSize = 0
    ELSE IF (@OuterPageSize > @PageSize)
        SET @OuterPageSize = @PageSize
    
    DECLARE @sql NVARCHAR(8000)
    
    SET @sql = 'SELECT * FROM
    (
        SELECT TOP ' + CAST(@OuterPageSize AS nvarchar(5)) + ' * FROM
        (
            SELECT TOP ' + CAST(@InnerPageSize AS nvarchar(5)) + ' * FROM <TABLE> ORDER BY <column> ASC
        ) AS t1 ORDER BY <column> DESC
    ) AS t2 ORDER BY <column> ASC'
    
    PRINT @sql
    EXECUTE sp_executesql @sql
    

    It wasn't elegant, and it wasn't fast, but it worked.

    0 讨论(0)
  • 2020-11-22 06:32

    In Sybase SQL Anywhere:

    SELECT TOP 1 START AT n * from table ORDER BY whatever
    

    Don't forget the ORDER BY or it's meaningless.

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