简体   繁体   English

SQL Server 2008中带有随机顺序的SQL查询结果分页

[英]SQL Query results pagination with random Order by in SQL Server 2008

I am trying to implement pagination to a page on my website that returns results from a database table. 我正在尝试对网站上的页面进行分页,该页面从数据库表返回结果。

Currently, it returns all rows in a random order. 当前,它以随机顺序返回所有行。 However, as my database is growing, I want to paginate these results instead of displaying them all on one page. 但是,随着数据库的增长,我想对这些结果进行分页,而不是将它们全部显示在一页上。 However, I don't want to return all results just to display 20 records for instance. 但是,我不想返回所有结果只是为了显示20条记录。 Depending on the page, I want take just the 20 records from the database that are relevant. 根据页面的不同,我只想从数据库中获取20条相关记录。

I'm following this tutorial: Tutorial 我正在关注本教程: 教程

However, the I cannot use the query with the OFFSET clause, because the hosting uses SQL SERVER 2008. (It is introduced in 2012 i believe). 但是,我不能将查询与OFFSET子句一起使用,因为托管使用SQL SERVER2008。(我相信它是在2012年引入的)。

I tried following the answer to this Question , but I want the results in a random order, and I cannot do an ORDER BY on a derived table... so I'm a bit stuck for ideas! 我尝试按照此问题的答案进行操作,但是我希望结果以随机顺序出现,并且我无法对派生表执行ORDER BY ...所以我有些想法了!

Any help? 有什么帮助吗? Thanks! 谢谢!

This is what I currently have: 这是我目前拥有的:

    SELECT Title, Filename, PhotoURL, Orientation, FolderName, SetURL, RowNum
      FROM (
            SELECT  p.Title, p.Filename, p.URL AS PhotoURL, p.Orientation, s.FolderName, s.URL AS SetURL, ROW_NUMBER() OVER (ORDER BY p.PhotoID) AS RowNum
          FROM  Photos p
                LEFT OUTER JOIN SetPhotos sp
                    ON sp.PhotoID = p.PhotoID
                LEFT OUTER JOIN [Sets] s
                    ON s.SetID = sp.SetID
         WHERE  p.Hide = 0
      ORDER BY  NEWID()
        ) AS PaginatedPhotos
 WHERE  PaginatedPhotos.RowNum BETWEEN 0 AND 10
  1. Add integer column 'order' to your table 将整数列“ order”添加到表中
  2. Write a code that fills this column in all rows with unique random numbers 编写代码以唯一的随机数填充所有行中的此列
  3. Run this code from time to time to shuffle your rows 时不时地运行此代码以随机排列行
  4. Make pagination as usual while sorting by 'order' 按“顺序”排序时照常进行分页

Keep in mind that the same rows can appear on different pages if you shuffle rows in the middle of someone paginating. 请记住,如果您在某人分页的中间打乱行,则相同的行会出现在不同的页面上。

Just select TOP(pagesize) . 只需选择TOP(pagesize) Since your order is random, requesting page=2 does not result in the page 2 of the original result that displayed page 1. In other words when the order is random and changes each time then page 1 is always correct for any page requested. 由于您的订单是随机的,因此请求page = 2不会导致显示第1页的原始结果的页面2。换句话说,当订单是随机的并且每次更改时,页面1始终对所请求的任何页面都是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM