Selecting Nth Record in an SQL Query

后端 未结 12 749
悲&欢浪女
悲&欢浪女 2020-12-28 23:33

I have an SQL Query that i\'m running but I only want to select a specific row. For example lets say my query was:

Select * from Comments

L

相关标签:
12条回答
  • 2020-12-28 23:55

    Well, in T-SQL (the dialect for SQL Server) you can do the following:

    SELECT TOP 1 *
      FROM (SELECT TOP 8 *
              FROM Table
             ORDER
                BY SortField)
     ORDER
        BY SortField DESC
    

    This way you get the 8th record.

    0 讨论(0)
  • 2020-12-28 23:58

    From the SELECT reference, use the LIMIT keyword:

    SELECT * FROM tbl LIMIT 5,10;  # Retrieve rows 6-15
    SELECT * FROM tbl LIMIT 5;     # Retrieve first 5 rows
    

    Note: this is for MySQL, other SQL engines may have a different keyword.

    0 讨论(0)
  • 2020-12-28 23:59

    First, you should say which RDBMS you're using.

    Second, you should give careful thought to what it is you're trying to accomplish. Relational Databases are set-based. In general, the order of elements in a set does not matter. You'll want to ask why it matters in this case, then see if there's a better way to embed the concept of order into the query itself.

    For instance, in SQL Server 2005 (and other RDBMS), you can use the ROW_NUMBER function to assign a sequential number to each row returned, based on the criteria you specify. You could then select rows based on the row number. Example from Books Online:

    USE AdventureWorks;
    GO
    WITH OrderedOrders AS
    (
        SELECT SalesOrderID, OrderDate,
        ROW_NUMBER() OVER (ORDER BY OrderDate) AS 'RowNumber'
        FROM Sales.SalesOrderHeader 
    ) 
    SELECT * 
    FROM OrderedOrders 
    WHERE RowNumber BETWEEN 50 AND 60;
    
    0 讨论(0)
  • 2020-12-29 00:01

    I have read the question & your comments on you would want next 3 blog comments etc.

    How is your tables structured?
    Assume that you have blog post Id & comment Id is generated in ascending order for each blog post, you could do a SELECT based on the current Id.

    e.g. if the blogpostId = 101, you get the top 3 comments order by posted Id. Now lets say, you want to get the next 3 comments - you could do a SELECT WHERE commentId between the last comment id shown TO the comment id - 3

    But all that depends on how your tables are defined.

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

    In SQL 2000 where you do not have ROW_NUMBER() function you could use a work-around like this:

    SELECT CommentsTableFieldList, IDENTITY(INT, 1,1) as seqNo 
    INTO #SeqComments 
    FROM Comments
    
    SELECT * FROM #SeqComments 
    WHERE seqNo = 8
    
    0 讨论(0)
  • 2020-12-29 00:04

    try This

    Let us assume , We want select 5th row of WC_Video Table And

    Select * from (Select Row_Number() over (Order by Uploadedon) as 'rownumber',* from Wc_Video )as Temp where rownumber=5
    
    0 讨论(0)
提交回复
热议问题