【问题标题】:Best Way to get total records count using SQL Query while paging data在分页数据时使用 SQL 查询获取总记录数的最佳方法
【发布时间】:2013-11-27 05:41:29
【问题描述】:

我在每页包含 15 行的页面上显示数据。我正在使用 SQL Server 2012 的 OFFSETFETCH 关键字来限制我想要的 15 行。但是,我想显示可用的总行数,如何在单个查询中执行此操作?

例如,在页面顶部,您正在查看 1505 条记录中的 15 条。

有没有办法可以将它与我现有的查询结合起来?

【问题讨论】:

  • 我通过使用 SQLDataReader 并查询两个单独的表解决了这个特定的场景。一个表有 15 条记录,然后另一个查询使用 Count() 函数调用总记录。

标签: sql sql-server-2012 paging fetch offset


【解决方案1】:

正如其他人所展示的那样,您可以这样做,但不是像他们展示的那样使用COUNT,我将利用系统元数据,这要快得多。从物理上讲,调用SELECT COUNT(1) AS rc FROM MyTable 将强制存储引擎枚举所有可能在内存中或不在内存中的数据以执行计数并等待任何独占锁被解锁。

你知道什么更有效吗?只看 sys.allocation_units。

SELECT
    s.[Name] as [Schema] 
,   t.[name] as [Table] 
,   SUM(p.rows) as [RowCount] 
FROM
    sys.schemas s 
    LEFT OUTER JOIN 
        sys.tables t 
        ON s.schema_id = t.schema_id 
    LEFT OUTER JOIN 
        sys.partitions p 
        ON t.object_id = p.object_id 
    LEFT OUTER JOIN  
        sys.allocation_units a 
        ON p.partition_id = a.container_id 
WHERE
    p.index_id  in(0,1) -- 0 heap table , 1 table with clustered index 
    AND p.rows is not null
    AND a.type = 1  -- row-data only , not LOB 
GROUP BY 
    s.[Name] 
,   t.[name] 
ORDER BY 
    1 
,   2; 

h/t 给 bimonkey 发帖 Count the number of rows in every Table in a Database in no time!

如果您想要一个执行此操作的“单一”查询,那么您需要将上述内容与您的偏移量和获取相结合。

在 SQL 中,不要将更少的代码行等同于更低的复杂性或更好的性能来愚弄。

我已经注释了以下查询,因为它真的很简单。

-- Create variables for our usage
-- http://technet.microsoft.com/en-us/library/ms188927.aspx
DECLARE @OFFSET int = 30
,   @FETCH int = 15;

-- Notice the previous statement ends with a semicolon (;)
-- The following structure is a Common Table Expression (CTE)
-- Think of it as a single use View
-- http://technet.microsoft.com/en-us/library/ms190766(v=sql.105).aspx
WITH COUNTS AS
(
    -- This query provides the number of rows in all the tables
    -- in the current catalog. It is screaming cheetah wheelies fast 
    -- as it does not need to physically read each row from each table
    -- to generate counts. Instead, it is using system metadata to 
    -- derive the row count.
    -- After the closing ), I will have access to a tabular structure
    -- called COUNTS 
    SELECT
        s.[Name] as [Schema] 
    ,   t.[name] as [Table] 
    ,   SUM(p.rows) as [RowCount] 
    FROM
        -- http://technet.microsoft.com/en-us/library/ms176011.aspx
        sys.schemas s 
        LEFT OUTER JOIN 
            -- http://technet.microsoft.com/en-us/library/ms187406.aspx
            sys.tables t 
            ON s.schema_id = t.schema_id 
        LEFT OUTER JOIN 
            -- http://technet.microsoft.com/en-us/library/ms175012.aspx
            sys.partitions p 
            ON t.object_id = p.object_id 
        LEFT OUTER JOIN  
            -- http://technet.microsoft.com/en-us/library/ms189792.aspx
            sys.allocation_units a 
            ON p.partition_id = a.container_id 
    WHERE
        p.index_id  in(0,1) -- 0 heap table , 1 table with clustered index 
        AND p.rows is not null
        AND a.type = 1  -- row-data only , not LOB 
    GROUP BY 
        s.[Name] 
    ,   t.[name] 
)
SELECT
    T.*
,   @OFFSET AS StartingRow
,   @FETCH AS PageSize
-- A subquery that uses the CTE above to extract our table's total row count
-- The table and schema below must align with the value in your FROM clause
-- http://technet.microsoft.com/en-us/library/ms189575(v=sql.105).aspx
,   (SELECT C.[RowCount] FROM COUNTS C WHERE C.[schema] = 'dbo' AND C.[Table] = 'MyTable') AS TotalRows
FROM
    dbo.MyTable T
ORDER BY
    1
-- http://technet.microsoft.com/en-us/library/gg699618.aspx    
OFFSET 30 ROWS
FETCH NEXT 15 ROWS ONLY;

【讨论】:

【解决方案2】:

对于使用 SQL Server 10.50 的用户,我可以通过公用表表达式 (CTE) 使用结果集来完成此操作。像这样的:

WITH resultSet AS     
(
SELECT 
   ROW_NUMBER() OVER(ORDER BY x.ID DESC) as Row, 
   x.other_fields
   FROM Table x    
   WHERE conditions_x
),
cte AS
(
   SELECT TOP 1 Row AS cte_row FROM resultSet ORDER BY Row DESC
)
-- And finally:
SELECT cte.cte_row AS Total, * FROM resultSet CROSS JOIN cte 
WHERE Row BETWEEN 11 AND 20; -- Rows between 11 and 20, for example. Those would be your previously computed START and END row variables.

这应该作为一个查询执行。

虽然我还没有在 SQL Server 2012 中尝试过,但我认为它也可以工作。

【讨论】:

    【解决方案3】:

    你可以使用COUNT():

    SELECT COUNT(*) FROM Table
    WHERE conditionHere
    

    然后您必须使用您选择的编程语言来计算每页数,例如 phpasp.net

    基本上计算是这样的:

    PageNumber * RecordsPerPage
    

    假设每页有 15 条记录的第 2 页将是:

    2 * 15
    

    所以,你的输出将是

    30 of NumberOfRecords
    

    你可以通过使用公式的方式来计算页面

    TotalPages = CEILING(TotalRecords / RecordsPerPages)
    

    例如使用你自己的数字,它会是:

    TotalPages = CEILING(1,505 / 15)
    

    如果你得到了上限,那是101

    如果Php 它可能看起来像这样:

    $TotalPages = Ceil($NumberOfRecords / $RecordsPerPages)
    

    如果ASP 使用C#,它可能看起来像这样:

    int TotalPages = Math.Ceil(NumberOfRecords/RecordsPerPages);
    

    但是,如果他们舔了最后一个被点击的页面,那么你可以简单地说:

    TotalRecords of TotalRecords
    

    例如:

    1,505 of 1,505
    

    【讨论】:

      猜你喜欢
      • 2016-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-29
      • 1970-01-01
      • 2013-05-06
      • 1970-01-01
      • 2013-05-01
      相关资源
      最近更新 更多