1

我正在寻找一些关于加快 SQL Azure 查询速度的建议。这是我们正在运行的两个查询的示例,当我们在其中添加 WHERE 子句时,查询会停止。

TheTime 和 orderType 这两个列都被编入索引。任何人都可以建议如何使这些运行更快,或者对查询做些什么以提高效率?

5.2 秒:

sum(cast(theTime AS INT)) as totalTime from Orders

20.2 秒:

 sum(cast(theTime AS INT)) as totalTime from Orders WHERE orderType='something_in_here'

以下是相关信息:

CREATE TABLE [dbo].[Orders] (
[ID] int IDENTITY(1,1) NOT NULL,
[orderType] nvarchar(90) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[orderTime] nvarchar(90) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,

CONSTRAINT [PrimaryKey_fe2bdbea-c65a-0b85-1de9-87324cc29bff] PRIMARY KEY CLUSTERED ([ID]) 
WITH (IGNORE_DUP_KEY = OFF)
)
GO
CREATE NONCLUSTERED INDEX [orderTime]
ON [dbo].[Orders] ([orderTime] ASC)
WITH (IGNORE_DUP_KEY = OFF,
STATISTICS_NORECOMPUTE = OFF,
ONLINE = OFF)
GO
CREATE NONCLUSTERED INDEX [actiontime_int]


CREATE NONCLUSTERED INDEX [orderType]
ON [dbo].[Orders] ([orderType] ASC)
WITH (IGNORE_DUP_KEY = OFF,
STATISTICS_NORECOMPUTE = OFF,
ONLINE = OFF)
GO
4

1 回答 1

1

I suspect your query is not doing what you think. It is taking the first million counts, rather than the count of the first million rows. I think you want:

select sum(cast(theTime AS INT))
from (select top (1000000) Orders
      from Orders
     ) t

versus:

select sum(cast(theTime AS INT))
from (select top  (1000000) Orders
      from Orders
      WHERE orderType='something_in_here'
     ) t

My suspicion is that using the index actually slows things down, depending on the selectivity of the where clause.

In the original query, you are reading all the data, sequentially. This is fast, because the pages just cycle through the processor.

Going through the index slows things down, because the pages are not read in order. You may be still be reading all the pages (if every page has a matching row), but they are no longer being read in "physical" or "logical" order. They are being read in the order of the index -- which is likely to be random.

于 2013-05-17T14:25:38.237 回答