我正在尝试编写一个查询来实现分页,我的基本要求是我需要一个查询,我可以给出最小和最大行范围,例如:对于第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
我在修理它时迷路了,有人可以指出错误。 谢谢!
答案 0 :(得分: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
答案 1 :(得分:1)
我认为问题是在[student] b
中添加了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
此外,您可能需要考虑将其包装在过程或函数中,以便更改范围。
答案 2 :(得分: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