复杂查询的sql性能

时间:2013-07-15 09:27:07

标签: sql-server

我有一张如下表:

CREATE TABLE MetalTemprature(
    idMetalTemprature int
    rawTime bigint NOT NULL,
    metal nchar(7) NOT NULL,
    color nchar(5) NOT NULL,
    Temp float NOT NULL)

和打击指数:

PRIMARY KEY CLUSTERED 
(
    idMetalTemprature ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON PRIMARY
) ON PRIMARY

CREATE NONCLUSTERED INDEX NonClusteredIndex1112 ON MetalTemprature
(
    rawTime DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON PRIMARY

当我运行此查询时需要0秒才能执行此操作:

SELECT  count(*)
  FROM MetalTemprature
  where rawTime < 4449449575 and  rawTime > (4449449575 -10000000) and  metal = 'iron';

但是当我把这个查询放在下面的其他选择

SELECT 
    SELECT  count(*)
          FROM MetalTemprature
          where rawTime < other.rawTime and  rawTime > (other.rawTime -10000000) and  metal = 'iron';
from other_table_only_one_row as other;

这需要大约60秒(当其他.rawTime只有4449449575且两个查询的结果相同时)为什么?

1 个答案:

答案 0 :(得分:0)

SELECT *
from other_table_only_one_row as other, (SELECT  count(*)
          FROM MetalTemprature
          where rawTime < other.rawTime and  rawTime > (other.rawTime -10000000) and  metal = 'iron') as cnt

将其放入FROM部分,只执行一次