SQL - 选择行范围

时间:2015-02-16 21:19:30

标签: sql

只是想就一些让我难以置信的事情提出一些建议。

例如,表“customers”有10,000行,如果我们要选择上半部分,我们可以从客户那里选择top(5000)*,但是如果我们需要选择接下来的5000行呢?

有什么想法吗?

谢谢,

2 个答案:

答案 0 :(得分:0)

按顺序排序并在降序中对其进行排序。

答案 1 :(得分:0)

如果您的表格恰好有10,000行,那么是,TOP 5000正常为您提供前5000个,如果您ORDER BY ... DESCENDING则为最后5000个。

然而,一般情况下,当您拥有数十万行并且一次只需要5000行时。这是您需要某种方式进行分页的时候。

通常,您需要一个整数行计数器,您可以将其与各种5000范围进行比较以获取页面。这可能是表中的实际列,其中包含从1到maxcustomer的行数;如果是这样你很好:

SELECT * FROM CUSTOMERS WHERE CustomerNumber BETWEEN 1 AND 5000
   ORDER BY CustomerNumber
SELECT * FROM CUSTOMERS WHERE CustomerNumber BETWEEN 5001 AND 10000
   ORDER BY CustomerBumber
SELECT * FROM CUSTOMERS WHERE CustomerNumber BETWEEN 10001 AND 15000
   ORDER BY CustomerBumber

(请记住,除非您提供ORDER BY子句,否则SELECT没有已定义的顺序!)

如果不这样做,那么(取决于您的SQL系统)您可以使用窗口化的SQL99函数生成一个:

SELECT * FROM (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY 1 ORDER BY CustomerNumber) AS RN
     FROM CUSTOMERS ) AS X WHERE X.RN BETWEEN 1 AND 5000
SELECT * FROM (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY 1 ORDER BY CustomerNumber) AS RN
     FROM CUSTOMERS ) AS X WHERE X.RN BETWEEN 5001 AND 10000
SELECT * FROM (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY 1 ORDER BY CustomerNumber) AS RN
     FROM CUSTOMERS ) AS X WHERE X.RN BETWEEN 10001 AND 15000

第三种方法是查看上次呼叫返回的最后一个CustomerNumber,并使用它来设置下一个呼叫:

SELECT TOP 5000 * FROM CUSTOMERS ORDER BY CustomerNumber
-- the app then captures the last number and feeds it back:
SELECT TOP 5000 * FROM CUSTOMERS WHERE CustomerNumber > nnnn

最后一种方式可能是最有效的,事实上,如果在CustomerNumber上有一个不错的索引。