2012-01-31 16 views
2

我有一個SELECT語句的問題。我發現,如果我有一行數據作爲結果,並使用ORDER BY,它會減慢它的速度。只要我刪除ORDER BY或添加另一行數據,它會在合理的時間內返回它。我返回的大部分數據將有不止1個結果(因此限制2),但有些情況下,只有一個單獨的行,它是拖延的東西。MYSQL永久發送數據。刪除ORDER BY或插入新行更快

Profiling 
Status Time 
starting 0.000082 
checking permissions 0.000007 
Opening tables 0.000020 
System lock 0.000016 
init 0.000043 
optimizing 0.000021 
statistics 0.000016 
preparing 0.000016 
executing 0.000004 
Sorting result 0.000005 
Sending data 15.276259 
end 0.000013 
query end 0.056590 
closing tables 0.000030 
freeing items 0.000156 
logging slow query 0.000008 
logging slow query 0.000007 
cleaning up 0.000009 

Showing rows 0 - 0 (1 total, Query took 15.3337 sec) 

SELECT expiration, strike, category, last, volume, stock_price 
FROM chains 
WHERE option_id = 'AMZN^^120203P00165000' 
AND DATE(id) = DATE(NOW()) 
AND TIME(id) BETWEEN '09:30:00' AND '16:00:00' 
ORDER BY id DESC 
LIMIT 2 

當我插入新行具有相同的option_id值和不同的ID(時間戳)值的結果是這樣的:

Showing rows 0 - 1 (2 total, Query took 0.2272 sec) 

或者如果我刪除ORDER BY ID DESC它返回類似的計時結果,小於一秒。

​​3210

的SQL EXPLAIN:

id select_type table type possible_keys key  key_len ref rows Extra 
1 SIMPLE  chains index NULL   PRIMARY 27  NULL 2 Using where 

表結構:

CREATE TABLE IF NOT EXISTS `chains` (
    `id` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, 
    `option_id` varchar(21) NOT NULL, 
    `symbol` char(4) NOT NULL, 
    `expiration` date NOT NULL, 
    `strike` decimal(10,2) NOT NULL, 
    `category` char(1) NOT NULL, 
    `last` decimal(10,2) NOT NULL, 
    `volume` int(50) NOT NULL, 
    `openint` int(50) NOT NULL, 
    `stock_price` decimal(12,2) NOT NULL, 
    `stock_volume` int(20) NOT NULL, 
    PRIMARY KEY (`id`,`option_id`) 
) ENGINE=MyISAM DEFAULT CHARSET=latin1; 

在年底,即時通訊試圖抓住 「最新」 兩種結果。

非常感謝您的幫助!非常感謝!

回答

0

通過配置文件顯示的階段定義文檔非常稀少,但從我發現的情況來看,很可能這些時間並不完全是其各自操作上花費的時間,而是來自上次操作的時間到指定操作的開始。這意味着發送數據並不是真的需要這麼長時間,而是實際上是排序,因爲查詢不使用索引,所以這很有意義。 ORDER BY需要很長的時間,因爲它必須掃描整個表並對其進行排序,然後才能確定哪些是前兩行;沒有它,它只是使用它找到的前兩行。

使用此查詢,您至少應該使用option_id上的索引。 option_idid上的多個索引可能會顯着提高此查詢的性能。

P.S.去找礦塊死靈!