I will try to explain myself quickly. I have a database called 'artikli' which has about 1M records. On this table i run a lots of different queryies but 1 particular is causing problems (long execution time) when ORDER by is present.
This is my table structure:
CREATE TABLE IF NOT EXISTSartikli(idint(11) NOT NULL,namevarchar(250) NOT NULL,datumdatetime NOT NULL,kategorije_idint(11) default NULL,id_valuteint(11) default NULL,podogovoruint(1) default '0',cijenadecimal(10,2) default NULL,valutaint(1) NOT NULL default '0',cijena_rezervadecimal(10,0) NOT NULL,cijena_kupidecimal(10,0) default NULL,cijena_akcijadecimal(10,2) NOT NULL,periodint(3) NOT NULL default '30',dostupnostenum('svugdje','samobih','samomojgrad','samomojkanton') default 'svugdje',zemljavarchar(10) NOT NULL,slikevarchar(500) NOT NULL,od_svarchar(34) default NULL,od_idint(10) unsigned default NULL,vrstaint(1) default '0',trajanjedatetime default NULL,izbrisanint(1) default '0',zakljucanint(1) default '0',prijavaint(3) default '0',izdvojendecimal(1,0) NOT NULL default '0',izdvojen_kaddatetime NOT NULL,izdvojen_datumdatetime NOT NULL,sajtint(1) default '0', PRIMARY KEY (id), KEYbrend(brend), KEYkanton(kanton), KEYdatum(datum), KEYcijena(cijena), KEYkategorije_id(kategorije_id,podogovoru,sajt,izdvojen,izdvojen_kad,datum) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
And this is the query:
SELECT artikli.datum as brojx,
artikli.izdvojen as i,
artikli.izdvojen_kad as ii,
artikli.cijena as cijena, artikli.name
FROM artikli
WHERE artikli.izbrisan=0 and artikli.prodano!=3
and artikli.zavrseno=0 and artikli.od_id!=0
and (artikli.sajt=0 or (artikli.sajt=1 and artikli.dostupnost='svugdje'))
and kategorije_id IN (18)
ORDER by i DESC, ii DESC, brojx DESC
LIMIT 0,20
What i want to do is to avoid Filesort which is very slow.
The problem is that you don't have an index on the
izdvojen,izdvojen_kadanddatumcolumns that are used by theORDER BY.Note that the large index you have starting with
kategorije_idcan't be used for sorting (although it will help somewhat with the where clause) because the columns you are sorting by are at the end of the index.