2016-02-28 27 views
2

以下查詢運行速度慢(超過五秒鐘)以約五百萬條記錄在每個表:優化MySQL的加入帶濾波器和訂單上不同的表

SELECT DISTINCT `items`.* 
FROM `items` 
INNER JOIN `tags` ON `tags`.`item_id` = `items`.`id` 
WHERE `tags`.`name` = '...' 
ORDER BY `items`.`stars` DESC LIMIT 64; 

我不清楚的最佳策略指數。我最初的想法是增加一個複合索引items.id + items.stars和複合索引tags.item_id + tags.name - 但這並沒有顯着減少查詢時間。我在所有外鍵索引和items.starstags.name索引。

EXPLAIN顯示我的兩個指標(index_tags_on_item_id_and_nameindex_items_on_id_and_stars)作爲可能的密鑰,但沒有使用:

1 | SIMPLE | tags | ref | index_tags_on_name | 5 | const  | 326538 | Using where; Using temporary; Using filesort 
2 | SIMPLE | items | eq_ref | PRIMARY   | 4 | tags.item_id | 1  | 

如何繼續進行,一面和秩序的標準在加入任何想法或最佳實踐另一個?我現在唯一的想法是複製tags中的stars

+0

你確定你需要'DISTINCT'? –

回答

0

如果您打算選擇只有一張桌子的列,您爲什麼需要首先連接兩張桌子?而是嘗試像這樣的子查詢:

select * from items where id in (select item_id from tags where tags.name = '...' 
) order by items.stars desc limit 64 

不知道它是否會改善性能,但值得嘗試。

0

你可以重新安排查詢趁你index(tags.item_id,tags.name)

SELECT DISTINCT `items`.* 
FROM `items` WHERE EXISTS 
    (SELECT 1 FROM `tags` WHERE `tags`.`item_id` = `items`.`id` 
     AND `tags`.`name` = '...') 
ORDER BY `items`.`stars` DESC LIMIT 64;