Gute Frage.
Indizes funktionieren von links nach rechts, also Ihr WHERE
Kriterien würden den Index verwenden. Die Sortierung würde in diesem Fall auch den Index verwenden (Ausführungsplan unten).
Aus dem Handbuch :
Wenn Sie einen Einzelspaltenindex (accountid
), würde stattdessen eine Dateisortierung verwendet. Daher profitiert Ihre Abfrage von diesem Index.
Zweispaltiger Index
create table t1 (
accountid tinyint,
logindate date);
create index idx on t1 (accountid, logindate);
insert into t1 values (1, '2012-09-05'), (2, '2012-09-09'), (3, '2012-09-04'),
(1, '2012-09-01'), (1, '2012-09-26'), (2, '2012-05-16'),
(1, '2012-09-01'), (3, '2012-10-19'), (1, '2012-03-01')
Ausführungsplan
ID SELECT_TYPE TABLE TYPE POSSIBLE_KEYS KEY KEY_LEN REF ROWS FILTERED EXTRA 1 SIMPLE t1 ref idx idx 2 const 5 100 Using where; Using index
Einspaltiger Index
create table t1 (
accountid tinyint,
logindate date);
create index idx on t1 (accountid);
insert into t1 values (1, '2012-09-05'), (2, '2012-09-09'), (3, '2012-09-04'),
(1, '2012-09-01'), (1, '2012-09-26'), (2, '2012-05-16'), (1, '2012-09-01'),
(3, '2012-10-19'), (1, '2012-03-01')
Ausführungsplan
ID SELECT_TYPE TABLE TYPE POSSIBLE_KEYS KEY KEY_LEN REF ROWS FILTERED EXTRA 1 SIMPLE t1 range idx idx 2 5 100 Using where; Using filesort