简体   繁体   中英

Avoiding mysql filesort

I have a client running a php photo gallery (on php 5.5, mysql 5.5, using myisam tables) that uses the directory tree method. Unfortunately, some of the queries in their gallery application is demanding horribly long filesorts. The offending query:

SELECT `name`, `slug` 
FROM `db_table` 
WHERE `left_ptr` <= '914731' 
  AND `right_ptr` >= '914734' 
  AND `id` <> 1 
ORDER BY `left_ptr` ASC

There are indexes on id, left_ptr and right_ptr, but according to the EXPLAIN, none of them are being used in the query.

I heard that creating a composite index (on the 'condition' columns) would make things faster, but does that apply to this case? The last condition is really but an 'anything but 1' clause, so would a composite index apply to that, too? Thanks for any insight into this.

Yes, a composite index on (left_ptr, right_ptr) should make this query run better.

MySQL will only use one index per query . It's likely not using any single index because it's determined no single index would be much faster than a full table scan. For example, id <> 1 is every row but the first, so just do a full table scan. The other two filters depend on how the data is distributed, but if it doesn't filter a significant portion of the table it won't use an index.

A composite index on (left_ptr, right_ptr) should make this query run better. Don't bother with id , as above id <> 1 only filters one row.

MySQL can use the first column of a composite index alone, so this composite index also replaces the one on left_ptr alone

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