I have a big table (around 70milion records) and I want to get some result in a order from database.
Here is my query
SELECT *
FROM `comment`
WHERE `account_id` IN ('accountId1','accountId2')
ORDER BY `date` desc, `id` desc
LIMIT 20;
I'm trying to get comments for specific account and I need to order them by date
and if they have same date
I need to order them by id
desc.
I added index to improve the query like this:
ALTER TABLE `comment`
ADD INDEX `account_id` (`account_id`, `date`, `id`);
My problem is it used filesort
for sorting result and it's not using index.
Here is the explain query
+----+-------------+--------------------+------------+-------+---------------+------------+---------+------+-------+----------+---------------------------------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+--------------------+------------+-------+---------------+------------+---------+------+-------+----------+---------------------------------------+
| 1 | SIMPLE | np_account_comment | NULL | range | account_id | account_id | 5 | NULL | 20757 | 100.00 | Using index condition; Using filesort |
+----+-------------+--------------------+------------+-------+---------------+------------+---------+------+-------+----------+---------------------------------------+
In the explain it said key_len
is 4
so its only use first part of index (account_id
) as index and its not using date
and id
for sorting.
Here is what I understood
- Its not depend on order by desc, I tested on order by asc and it has same result.
- The problem probably is because of
account_id IN ('accountId1','accountId2')
because when I using ``account_id= 'accountId1'
I have these result
+----+-------------+--------------------+------------+------+----------------------+------------+---------+-------------+------+----------+---------------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+--------------------+------------+------+----------------------+------------+---------+-------------+------+----------+---------------------+
| 1 | SIMPLE | comment | NULL | ref | account_id | account_id | 4 | const,const | 1 | 100.00 | Backward index scan |
+----+-------------+--------------------+------------+------+----------------------+------------+---------+-------------+------+----------+---------------------+
Still key_len
is 5 but in extra it doesnt said filesort
How I can improve my query speed? sometime it take 20sec to complete.
If I'm current when mysql used full index the key_len
should be 13
( 4(INT) * 2 + 5 (DATETIME) )