我正在使用SQL Server 2012版。我有一个超过1000万行的表。我必须使用SQL过滤器计算记录。
我的疑问是:
select count(*)
from reconcil
where tenantid = 101
对于5百万条记录花费超过5分钟。
有没有最快的方法来记录记录?
Reconcil
表结构是
CREATE TABLE [dbo].[RECONCIL]
(
[AckCode] [nvarchar](50) NULL,
[AckExpireTime] [int] NULL,
[AckFileName] [nvarchar](255) NULL,
[AckKey] [int] NULL,
[AckState] [int] NULL,
[AppMsgKey] [nvarchar](30) NULL,
[CurWrkActID] [nvarchar](50) NULL,
[Date_Time] [datetime] NULL,
[Direction] [nvarchar](1) NULL,
[ErrorCode] [nvarchar](50) NULL,
[FGLOGKEY] [int] NOT NULL,
[FolderID] [int] NULL,
[FuncGCtrlNo] [nvarchar](14) NULL,
[INLOGKEY] [int] NULL,
[InputFileName] [nvarchar](255) NULL,
[IntCtrlNo] [nvarchar](14) NULL,
[IsAssoDataPresent] [nvarchar](1) NULL,
[JobState] [int] NULL,
[LOGDATA] [nvarchar](max) NULL,
[MessageID] [nvarchar](25) NULL,
[MessageState] [int] NULL,
[MessageType] [int] NULL,
[NextWrkActID] [nvarchar](50) NULL,
[NextWrkHint] [nvarchar](20) NULL,
[NONFAERRORLOG] [nvarchar](max) NULL,
[NumberOfBytes] [int] NULL,
[NumberOfSegments] [int] NULL,
[OutputFileName] [nvarchar](255) NULL,
[Priority] [nvarchar](1) NULL,
[ReceiverID] [nvarchar](30) NULL,
[RecNo] [int] NULL,
[RecordID] [int] IDENTITY(1,1) NOT NULL,
[RelationKey] [int] NULL,
[SEGLOG] [nvarchar](max) NULL,
[SenderID] [nvarchar](30) NULL,
[ServerID] [nvarchar](255) NULL,
[Standard] [int] NULL,
[TenantID] [int] NULL,
[TPAgreementKey] [int] NULL,
[TSetCtrlNo] [nvarchar](35) NULL,
[UserKey1] [nvarchar](255) NULL,
[UserKey2] [nvarchar](255) NULL,
[UserKey3] [nvarchar](255) NULL,
CONSTRAINT [RECONCIL_PK]
PRIMARY KEY CLUSTERED ([RecordID] ASC)
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
答案 0 :(得分:0)
根据建议,如果您有这么多项目,请通过tenantId创建索引甚至对您的表进行分区。这样,每个分区就有一个数据文件可以提高性能。
答案 1 :(得分:0)
除非您实现了计数,否则TenentID上的这个非聚集索引将提供更好的性能,因为它比聚簇主键索引更窄,并且只扫描匹配的行:
CREATE INDEX idx ON [dbo].[RECONCIL](TenantID);
如果使用此索引的聚合查询的性能不可接受,则可以使用计数创建索引视图。索引视图将为此查询提供最快的性能,但会为插入和删除的存储和索引维护带来额外的成本。此外,修改表的查询必须具有required SET options for indexed views。如果经常执行计数查询,那么这些成本可能是合理的。
SQL Server可以在Enterprise(或Developer)版本中自动使用索引视图,即使查询中没有直接引用,只要优化器可以使用视图匹配查询的语义。在较小的版本中,您需要直接查询索引视图并指定NOEXPAND
提示。
CREATE VIEW dbo.VW_RECONCIL_COUNT
WITH SCHEMABINDING
AS
SELECT
TenantID
, COUNT_BIG(*) AS TenentRowCount
FROM [dbo].[RECONCIL]
GROUP BY TenantID;
GO
CREATE UNIQUE CLUSTERED INDEX cdx ON dbo.VW_RECONCIL_COUNT(TenantID);
GO
--Enterprise Edition can use the view index automatically
SELECT COUNT_BIG(*) AS TenentRowCount
FROM [dbo].[RECONCIL]
WHERE TenantID = 101
GROUP BY TenantID;
GO
--other editions require the view to be specified plus the NOEXPAND hint
SELECT TenentRowCount
FROM dbo.VW_RECONCIL_COUNT WITH (NOEXPAND)
WHERE TenantID = 101;
GO
答案 2 :(得分:-2)
select count(tenantid)
from reconcil
where tenantid = 101 group by tenantid ;
不确定,但尝试使用它。