2016-02-28 61 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;