MySQL:按加入列分组的索引

问题描述:

我试图优化我的索引以进行JOIN,然后GROUP BY来自连接表中的一列。MySQL:按加入列分组的索引

我通过运行下面的脚本测试,玩索引,但我似乎无法弄清楚我需要第三个查询的索引。

求助:添加虚拟数据会使sql的行为有所不同,我之前尝试过的其中一个索引工作得很好!

CREATE DATABASE stats_idx_test; 

USE stats_idx_test; 

DROP TABLE stats; 
CREATE TABLE stats (article_id INT, cnt INT, type INT); 
ALTER TABLE stats ADD INDEX idxs1 (article_id, cnt, type); 

DROP TABLE article; 
CREATE TABLE article (id INT, cat_id INT); 
ALTER TABLE article ADD INDEX idxa2 (cat_id, id); 

INSERT INTO article (id, cat_id) VALUES (1, 1); 
INSERT INTO stats (article_id, cnt, type) VALUES (1, 9, 1); 
INSERT INTO stats (article_id, cnt, type) VALUES (1, 13, 2); 

EXPLAIN 
SELECT SUM(stats.cnt) 
FROM stats 
WHERE stats.type = 1 AND stats.article_id = 1; 
-- Using where; Using index 

EXPLAIN 
SELECT article.cat_id, SUM(stats.cnt) 
FROM stats 
JOIN article ON (stats.article_id = article.id) 
WHERE stats.type = 1 AND article.cat_id = 1; 
-- Using where; Using index 

EXPLAIN 
SELECT article.cat_id, SUM(stats.cnt) 
FROM stats 
JOIN article ON (stats.article_id = article.id) 
WHERE stats.type = 1 
GROUP BY article.cat_id; 
-- Using index 
-- Using where; Using index 
+0

实际的问题是什么?你我没有遇到问题,因为你没有把'stats.article_id = article.id'作为'stats.article_id = article.article.id'的范围' – 2013-03-07 17:48:43

+0

问题在于对于stats表它使用'idx2'但仍然有'在哪里使用;使用索引;使用临时;使用filesort' – 2013-03-08 08:19:49

添加虚拟数据会使sql的行为有所不同,我之前尝试的其中一个索引工作得很好!

对于您所在的组,您需要cat_id上的索引。您拥有的当前索引无法应用。

Group by and indexing

你也应该考虑ID的主键。

+0

我暂时忽略了PK,因为它是无关紧要的,尽管我明白它可以帮助其他一些目前不在我的测试场景中的JOIN。 – 2013-03-08 08:20:31

+0

我添加了'ALTER TABLE文章ADD INDEX idx4(cat_id);'但这并没有帮助,它需要成为一个多列idx我认为 – 2013-03-08 08:21:14