我在SQL Azure中有一个数据库,在15到30分钟之间做一个简单的操作:
select count(id) from mytable
数据库大约3.3GB,计数返回大约2,000,000,但我已在本地尝试过,只需不到5秒!
我也运行了一个:
ALTER INDEX ALL ON mytable REBUILD
在数据库中的所有表上。
如果有人能指出我试图诊断/解决这个问题,我将不胜感激。
(请跳到下面的更新3,因为我现在认为这是问题,但我仍然不明白)。
更新1:聚集索引扫描中99%的时间似乎如下图所示。我有
更新2:这就是我做的时候统计信息的回复:
SET STATISTICS IO ON
SET STATISTICS TIME ON
select count(id) from TABLE
统计:
SQL Server parse and compile time:
CPU time = 0 ms, elapsed time = 0 ms.
SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 0 ms.
SQL Server parse and compile time:
CPU time = 0 ms, elapsed time = 317037 ms.
SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 0 ms.
SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 0 ms.
(1 row(s) affected)
Table 'TABLE'. Scan count 1, logical reads 279492, physical reads 8220, read-ahead reads 256018, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
(1 row(s) affected)
SQL Server Execution Times:
CPU time = 297 ms, elapsed time = 438004 ms.
SQL Server parse and compile time:
CPU time = 0 ms, elapsed time = 0 ms.
SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 0 ms.
更新3:好的 - 我现在有另一种理论。 Azure门户建议每次我测试这个简单的选择查询时,它将我的DTU百分比最大化到接近100%。我正在使用性能级别为S1(20 DTU)的标准Azure SQL实例。这个简单的查询是否可能因我的DTU限制而变慢?
我意识到这是旧的,但我遇到了同样的问题。我有一个包含250万行的表,我从本地数据库导入Azure SQL并在S3级别运行。 Select Count(0) from Table
导致5-7分钟的执行时间与毫秒内部部署相比。
在Azure中,索引和表扫描似乎在性能上受到极大的惩罚,因此在查询中添加“无用的”WHERE
会强制它在聚簇索引上执行索引查找。
在我的情况下,这执行几乎相同的Select count(0) from Table where id > 0
导致性能匹配内部部署查询。
建议:尝试使用select count(*)
:它实际上可能会改善响应时间:
还有,你做过“解释计划”吗?
============更新============
感谢您获取统计信息。
你正在做2M行的全表扫描 - 不好:(
可能的解决方法:查询系统表row_count
:
select t.name ,s.row_count from sys.tables t
join sys.dm_db_partition_stats s
ON t.object_id = s.object_id
and t.type_desc = 'USER_TABLE'
and t.name not like '%dss%'
and s.index_id = 1
快速完善@FoggyDay帖子。如果您的表已分区,则需要对行数进行求和。
SELECT t.name, SUM(s.row_count) row_count
FROM sys.tables t
JOIN sys.dm_db_partition_stats s
ON t.object_id = s.object_id
AND t.type_desc = 'USER_TABLE'
AND t.name not like '%dss%'
AND s.index_id = 1
GROUP BY t.name