1

我正在尝试编写一个查询来实现分页,我的基本要求是我需要一个查询,我可以在其中给出要返回的最小和最大行范围,例如对于第 1 页我需要从 1-10 到第 11-20 页的记录等等等等。

通过互联网的一些帮助,在这里,我写下了以下查询,但它并没有真正按照它应该的方式工作,并且无论范围是多少,都会返回一大堆行(可能我在查询中缺少一些连接)

SELECT b.id,b.title,b.name
FROM (
    SELECT ROW_NUMBER() OVER(ORDER BY (select NULL as noorder)) AS RowNum, * 
    FROM [student] b
) as alias,[student] b,[class] c
WHERE b.[status]=1 
AND c.id=b.class 
AND c.name='Science' 
AND RowNum BETWEEN 1 AND 5
ORDER BY b.dtetme DESC

我在修复它时迷路了,有人可以指出错误。谢谢!

4

3 回答 3

1

您的整个查询逻辑 +ROW_NUMBER应该放在子查询中。您将外部WHERE用于分页。

ROW_NUMBER必须有ORDER BY在哪个页面上执行。

SELECT  a.id ,
        a.title ,
        a.name
FROM    
   ( 
        SELECT ROW_NUMBER() OVER (ORDER BY b.dtetme DESC) AS RowNum, b.*
        FROM  [student] b 
        INNER JOIN [class] c ON  c.id = b.class
        WHERE b.[status] = 1
        AND c.name = 'Science'
    ) a
WHERE RowNum BETWEEN 1 AND 10 -- change numbers here for pages
ORDER BY t.RowNum
于 2013-06-27T12:48:20.553 回答
1

[student] b我认为问题出在th 添加FROM,尝试将连接移动到子查询中。

SELECT a.id, a.title, a.name
FROM (
    SELECT ROW_NUMBER() OVER(ORDER BY (select NULL as noorder)) AS RowNum, * 
    FROM [student] b
    JOIN [class] c ON c.id = b.class
    WHERE b.[status]=1 
    AND c.name='Science' 
) as a
WHERE a.RowNum BETWEEN 1 AND 5
ORDER BY a.dtetme DESC

此外,您可能需要考虑将其包装在过程或函数中,以便更改范围。

于 2013-06-27T12:48:53.863 回答
0

看来你想要这样的东西:

SELECT t.id,t.title,t.name FROM (
    SELECT s.id,s.title,s.name, RowNum = ROW_NUMBER() OVER(ORDER BY s.dtetme DESC)
    FROM student s
    INNER JOIN class c ON c.id = s.class
    WHERE s.[status]=1 AND c.name='Science' ) AS t
WHERE t.RowNum BETWEEN 1 AND 5
ORDER BY t.RowNum
于 2013-06-27T12:50:24.850 回答