Simple query but can not get rid of "using filesort":
CREATE TABLE IF NOT EXISTS `online` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`uid` int(11) NOT NULL,
`expiration` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `uid` (`uid`),
KEY `expiration` (`expiration`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1925234 ;
mysql> explain SELECT i.id, i.uid, i.expiration, u.nick, u.mainpicture
-> FROM online i join usertable u on i.uid = u.id
-> order by i.expiration DESC limit 0,12;
+----+-------------+-------+--------+---------------+---------+---------+----------------+------+----------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+--------+---------------+---------+---------+----------------+------+----------------+
| 1 | SIMPLE | i | ALL | uid | NULL | NULL | NULL | 1020 | Using filesort |
| 1 | SIMPLE | u | eq_ref | PRIMARY | PRIMARY | 4 | dbasen01.i.uid | 1 | |
+----+-------------+-------+--------+---------------+---------+---------+----------------+------+----------------+
2 rows in set (0.00 sec)
"usertable"
has index on "id"
column. Tried to order by "i.id"
(primary key) but the same - query still uses filesort.
Update after RolandoMySQLDBA answer:
+----+-------------+-----------------+--------+---------------+---------+---------+-------+------+----------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-----------------+--------+---------------+---------+---------+-------+------+----------------+
| 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 12 | |
| 1 | PRIMARY | u | eq_ref | PRIMARY | PRIMARY | 4 | i.uid | 1 | |
| 2 | DERIVED | online | ALL | NULL | NULL | NULL | NULL | 1009 | Using filesort |
+----+-------------+-----------------+--------+---------------+---------+---------+-------+------+----------------+
Solution:
I deleted column "id" because it's not used. Then modified index:
ALTER TABLE online ADD INDEX expiration (expiration,uid);
Result:
+----+-------------+-------+--------+---------------+------------+---------+----------------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+--------+---------------+------------+---------+----------------+------+-------------+
| 1 | SIMPLE | i | index | uid | expiration | 8 | NULL | 12 | Using index |
| 1 | SIMPLE | u | eq_ref | PRIMARY | PRIMARY | 4 | dbasen01.i.uid | 1 | |
+----+-------------+-------+--------+---------------+------------+---------+----------------+------+-------------+
Thanks to all.
(expiration, uid)
? – ypercube Mar 15 at 7:01