使用where子句计算返回行的最快方法

时间:2015-10-13 08:51:13

标签: sql-server performance count query-optimization

我有一个带有这种结构的大型log4net数据库表。

    CREATE TABLE [dbo].[Log]
(
    [Id] [INT] IDENTITY(1,1) NOT NULL,
    [Date] [DATETIME] NOT NULL,
    [Thread] [VARCHAR](255) NOT NULL,
    [Level] [VARCHAR](50) NOT NULL,
    [Logger] [VARCHAR](255) NOT NULL,
    [Application] [VARCHAR](50) NOT NULL,
    [Server] [VARCHAR](50) NOT NULL,
    [Message] [VARCHAR](4000) NOT NULL,
    [Exception] [TEXT] NULL,
    [UserName] [NVARCHAR](50) NULL,
    [CorrelationId] [VARCHAR](255) NULL,
 CONSTRAINT [PK_Log] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)

但是这张表有250万行cca。我需要表的返回计数。标准方式是(由实体框架生成)

SELECT [GroupBy1].[A1] AS [C1]
FROM   (SELECT COUNT(1) AS [A1]
        FROM   [dbo].[Log] AS [Extent1]
        WHERE  ((([Extent1].[Level] = 'DEBUG')
                 AND ('DEBUG'  IS NOT NULL))
                 OR (([Extent1].[Level] = 'INFO')
                     AND ('INFO'  IS NOT NULL))
                 OR (([Extent1].[Level] = 'WARN')
                     AND ('WARN'  IS NOT NULL)))
                     OR (([Extent1].[Logger] = 'PlusService')
                         AND ('PlusService' IS NOT NULL))) AS [GroupBy1]

但非常缓慢,平均5分钟与litle在哪里。我需要使用where clausule。有可能我可以如何使用这样的系统计数方法吗?

SELECT CONVERT(bigint, rows)
FROM sysindexes
WHERE id = OBJECT_ID('Log')
AND indid < 2

或者

SELECT CAST(p.rows AS float)
FROM sys.tables AS tbl
INNER JOIN sys.indexes AS idx ON idx.object_id = tbl.object_id and idx.index_id < 2
INNER JOIN sys.partitions AS p ON p.object_id=CAST(tbl.object_id AS int)
AND p.index_id=idx.index_id
WHERE ((tbl.name=N'Log'
AND SCHEMA_NAME(tbl.schema_id)='dbo'))

或者

SELECT SUM (row_count)
FROM sys.dm_db_partition_stats
WHERE object_id=OBJECT_ID('Log')   
AND (index_id=0 or index_id=1);

我上面提到的这三个选项非常快。但我认为它不支持使用where子句。有什么方法可以使用这样的方法吗?

0 个答案:

没有答案