【问题标题】:SQL - Better approach for total records countSQL - 总记录数的更好方法
【发布时间】:2016-06-17 00:35:12
【问题描述】:

我编写了一个查询,我在其中获取记录以及总记录数。我有两种方法,但不知道哪一种更好更便宜

先有多个cte

;with allRecords as 
(
   -- query fetching all the records with many joins
),
recordsCount as 
(
    select count(*) as RecordsCount from allRecords
)
select * from allRecords, recordsCount

第二种方法,使用 cte 和交叉连接

;with allRecords as 
(
   -- query fetching all the records with many joins
)
select *, c.totalRecords from allRecords 
cross join (select count(*) as totalRecords from allRecords) c

我个人觉得第二种方法的性能稍微好一点。

所以在第一种方法中,是否每次都为第一个 cte 的所有记录调用第二个 cte,或者它只在第一个 cte 完成时运行一次?那么我认为使用第一种方法没有问题。

请提出建议!

【问题讨论】:

  • 不确定我是否完全理解了这个问题,但分析功能不适合您吗? COUNT(*) OVER()
  • @mcha 最初我只使用它,但这需要很多时间,所以我切换到 CTE
  • 有意思,你用其他方法成功实现了更好的性能吗?
  • @mcha - 是的,我提到的两种方法比这快得多

标签: sql sql-server tsql


【解决方案1】:

这种方法是将COUNTOVER 一起使用:

SELECT *, COUNT(*) OVER()
FROM --- rest of the query here

【讨论】:

  • 我最初使用的是count over,但这比这花费的时间要多得多,我的两种方法都需要大约 1-2 秒,而当我使用 count over 时需要 26 秒
【解决方案2】:

想法-1

sp_MSforeachtable 'sp_spaceused "?"'

想法-2

sp_MSforeachtable 'select ''?'' Tablename, count(*) ''Rows'' from ?';

想法-3

SELECT object_name(id), rows
FROM sysindexes
WHERE indid IN (0, 1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-03
    • 2017-08-11
    • 1970-01-01
    • 1970-01-01
    • 2014-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多