Skip to content

Instantly share code, notes, and snippets.

@rubensayshi
Last active December 14, 2015 21:29
Show Gist options
  • Save rubensayshi/5151544 to your computer and use it in GitHub Desktop.
Save rubensayshi/5151544 to your computer and use it in GitHub Desktop.
hmm, when doing a query with a JOIN and a WHERE, why does mysql only use an index for the JOIN part? Why does mysql chose to use the `idxa0` instead of using `idxa2`?
DROP TABLE article;
DROP TABLE cat;
CREATE TABLE cat (
id INT AUTO_INCREMENT,
weight INT,
PRIMARY KEY (`id`)
);
CREATE TABLE article (
id INT AUTO_INCREMENT,
cat_id INT,
score INT,
PRIMARY KEY (`id`)
);
ALTER TABLE article ADD INDEX idxa0 (cat_id);
ALTER TABLE article ADD INDEX idxa1 (cat_id, score);
ALTER TABLE article ADD INDEX idxa2 (score, cat_id);
INSERT INTO cat (id, weight) VALUES
(1, 6),
(2, 3);
INSERT INTO article (cat_id, score) VALUES
(1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1),
(2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1), (2, 1)
;
EXPLAIN
SELECT article.*
FROM article
WHERE cat_id = 1 AND score > 5;
EXPLAIN
SELECT article.*, cat.weight
FROM article, cat
WHERE article.cat_id = cat.id AND score > 5;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment