简体   繁体   中英

How to avoid Order by using temporary,filesort

What index do i need to create to avoid order by using temporary, filesort

  EXPLAIN SELECT   tid, sum(count)    
              FROM test  
                 WHERE cid = 1
                 GROUP BY tid
                 ORDER BY sum(count) DESC

   1    SIMPLE  test    ref     PRIMARY,id_UNIQUE,cid   cid     4   const   2   Using where; Using index; Using temporary; Using filesort

Create table :

   CREATE TABLE test(
           cid INT,
           tid INT,
            datedm INT,
           count INT,
            PRIMARY KEY(cid,tid,datedm),
           INDEX(cid,tid,count),
           UNIQUE INDEX id_UNIQUE(cid,tid,datedm)
          );

In this case you can't: the ORDER BY is on an aggregated value which can't be indexed as such.

Note your last index is identical to the primary key. However, if you reverse it to tid, cid it may help because GROUP BY implies an ORDER BY too. But, you may then have issues with the WHERE clause because of how MySQL works

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM