我有兩個表,應用程序和pricehistory 有一個主要索引id在應用程序上是一個int 在pricehistory我有兩個字段id_app(int),price(float )和dateup(日期)和一個唯一索引「id_app,dateup」Mysql使用filesort即使當使用索引和只有一行
我試圖讓一個應用程序的最新版本(日)價格:
select app.id,
( select price
from pricehistory
where id_app=app.id
order by dateup desc limit 1)
from app
where id=147
的解釋選擇是怎麼樣的奇怪,因爲它返回1行,但它仍然使一個文件夾:
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY app const PRIMARY PRIMARY 4 const 1
2 DEPENDENT SUBQUERY pricehistory ref id_app,id_app_2,id_app_3 id_app 4 const 1 Using where; Using filesort
爲什麼只有1行時需要filesort?爲什麼它的文件排序時我索引所有的IT需求(id_app和dateup)
應用程序有一個百萬行,我使用的是InnoDB
編輯:一個SQL小提琴說明問題:
http://sqlfiddle.com/#!2/085027/1
EDIT3: 新撥弄着同樣的問題另一個請求: http://sqlfiddle.com/#!2/f7682/6
edit4:這個小提琴(http://sqlfiddle.com/#!2/2785c/2)顯示建議的查詢不起作用,因爲它選擇了所有來自pricehistory的數據,只是爲了獲取我想要的數據。
什麼是你的MySQL版本?我已經在版本5.7上試過這個查詢,當「id_app,dateup」上的組合索引已經創建時,它沒有使用filesort。 – krokodilko
5.5.35-0 + wheezy1-log(Debian) – user3416510
我已經添加了一個帶有2個索引的sql小提琴,而mysql使用的是最長的索引而不是最短的,但我不知道爲什麼 – user3416510