2012-12-04 48 views
2

我從多個表中獲取數據,其中有600萬條記錄。但是需要花費很多時間來獲取它。 請讓我知道如何縮短取回時間。 我也使用了LIMIT情況,但仍然沒有改善。Mysql查詢花費大量時間獲取數據

我的查詢是:

SELECT DISTINCT 
tf_history.thefind_id, 
tf_product.product_id, 
tf_product.`name`, 
tf_product.product_url, 
tf_product.image_tpm, 
tf_product.image_thefind, 
tf_product.image_accuracy, 
(SELECT MIN(tf_h.price) 
FROM tf_history AS tf_h 
WHERE tf_h.thefind_id = tf_history.thefind_id) as price, 
oc_product.price AS priceTPM 
FROM tf_product 
LEFT JOIN tf_history ON tf_product.product_id = tf_history.product_id 
        AND tf_product.thefind_id = tf_history.thefind_id 
LEFT JOIN oc_product ON tf_product.product_id = oc_product.product_id 
WHERE tf_product.product_id = @product_id 

我的表:

tf_history 

history_id int(11) NO PRI  auto_increment 
thefind_id int(11) NO   
product_id int(11) NO   
price decimal(15,4) NO   
date datetime NO   

AND 
tf_product 

thefind_id int(11) NO PRI  auto_increment 
product_id int(11) NO   
name varchar(255) NO   
store_id int(11) NO   
product_url varchar(255) NO   
image_tpm varchar(255) NO   
image_thefind varchar(255) NO   
image_accuracy int(3) NO   
date datetime NO 

但是當我使用這個查詢:

SELECT * from tf_history 

我在0.641s得到了結果,那會是什麼是問題嗎? 當記錄較少時,第一個查詢運行平穩。

+1

什麼是表格定義?你有什麼指數?你在運行什麼樣的硬件?什麼是「很多很多時間」?秒?分鐘?小時? –

+0

我的硬件是雙核心 – Paz

+0

而你的磁盤IO系統是...軟盤? SATA?襲擊? NAS?與數據量相比,有多少內存?所有這些都可能很重要。 –

回答

0

移動子查詢列到一起

SELECT DISTINCT 
th.thefind_id, 
tp.product_id, 
tp.`name`, 
tp.product_url, 
tp.image_tpm, 
tp.image_thefind, 
tp.image_accuracy, 
th.price, 
op.price AS priceTPM 
FROM tf_product tp 
LEFT JOIN (SELECT thefind_id, product_id, MIN(price) as price 
      FROM tf_history 
      group by thefind_id, product_id) th ON tp.product_id = th.product_id 
               AND tp.thefind_id = th.thefind_id 
LEFT JOIN oc_product op ON tp.product_id = op.product_id 
WHERE tp.product_id = @product_id 
1

終於得到了結果,通過採用指數將解決您的問題索引