Domanda

My table:

CREATE TABLE test (
  id INT AUTO_INCREMENT,
  anotherID INT,
  PRIMARY KEY (id),
  INDEX testIndex (id, anotherID)
);
INSERT INTO test VALUES (1,1),(2,1),(3,1),(4,1);

My query:

EXPLAIN SELECT *
FROM test
WHERE id = 1
  AND anotherID = 1;

Per that only the PRIMARY key is being used. testIndex, however, is not. My question is... why? Since the SELECT is referencing values in both id and anotherID shouldn't testIndex be used?

The SQL fiddle:

http://sqlfiddle.com/#!2/b833d9/1

È stato utile?

Soluzione

The primary key is unique, so the additional check isn't even necessary. It doesn't get more unique than the primary key. So there is no additional benefit in this case to use the other index.

Altri suggerimenti

Well, MySql apparently believes that the primary key is sufficient for the query. However, you can do this:

EXPLAIN SELECT *
FROM test USE INDEX (textIndex) ...
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top