Selecting Nth Record in an SQL Query

后端 未结 12 950
悲&欢浪女
悲&欢浪女 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: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;
    

提交回复
热议问题