我现在有200万条记录,每天会增加0.05百万条记录,所以我想优化这个查询
Select * from Forex where Id in
(SELECT MAX(Id) FROM Forex GROUP BY Symbol having Symbol in
(Select Distinct Symbol from Forex) )
我创建了NONCLUSTERED INDEX,因此此查询所需的时间为673毫秒。我已将查询修改为
Select * from Forex where Id in
(SELECT MAX(Id) FROM Forex GROUP BY Symbol having Symbol in
('AUDCAD','AUDCHF','AUDJPY','AUDNZD','AUDUSD','CADCHF','CHFJPY',
'EURAUD','EURCAD','EURCHF','EURGBP','EURJPY','EURNOK','EURNZD',
'EURUSD','GBPCAD','GBPCHF','GBPJPY','GBPUSD','NZDJPY','NZDUSD',
'USDCAD','USDCHF','USDJPY','USDNOK','USDSEK'))
现在花费的时间是391毫秒
是否可以制作不到100毫秒?或者有人帮助优化此查询
答案 0 :(得分:1)
因为你只有26个符号和一百万行26个索引搜索可能更好(假设Symbol ASC, Id DESC
上的索引)
DECLARE @Id INT,
@Symbol VARCHAR(10)
DECLARE @Results TABLE(
Id INT,
Symbol VARCHAR(10))
SELECT TOP 1 @Id = Id,
@Symbol = Symbol
FROM Forex
ORDER BY Symbol ASC,
Id DESC
WHILE @@ROWCOUNT = 1
BEGIN
INSERT INTO @Results
VALUES (@Id,
@Symbol)
SELECT TOP 1 @Id = Id,
@Symbol = Symbol
FROM Forex
WHERE Symbol > @Symbol
ORDER BY Symbol ASC,
Id DESC
END
SELECT *
FROM @Results
答案 1 :(得分:0)
你应该能够摆脱HAVING
条款:
Select * from Forex where Id in
(SELECT MAX(Id) FROM Forex GROUP BY Symbol)
你也可以尝试这个版本:
SELECT * FROM Forex F
WHERE Id =
(SELECT MAX(Id) FROM Forex WHERE Symbol = F.Symbol)
虽然我不希望它有太大的不同。
一些广泛的描述(一些可能有用,有些可能没有):
Id
和Symbol, Id DESC
上拥有索引。如果Id
上的索引可以是CLUSTERED,那么它也会有所帮助。Symbol
移动到另一个较小的表