We have the following query:
SELECT * FROM bigtable WHERE IP='123.123.123.123' AND uniqueid='something' ORDER BY id DESC LIMIT 1;
Running an EXPLAIN on it results in:
+----+-------------+------
-------+--
----+-----
----------
--+-------
----------
+---------
+---------
----+-----
-+--------
----------
----------
-+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+------
-------+--
----+-----
----------
--+-------
----------
+---------
+---------
----+-----
-+--------
----------
----------
-+
| 1 | SIMPLE | bigtable | ref | IDX_IP_UNIQUEID | IDX_IP_UNIQUEID | 16 | const,const | 4390 | Using where; Using filesort |
+----+-------------+------
-------+--
----+-----
----------
--+-------
----------
+---------
+---------
----+-----
-+--------
----------
----------
-+
The table is just under 300,000 records right now. The IP and uniqueID fields are both varchar(100) fields, but are often less than 20 characters in length (but not always), so I created a combo index called IDX_IP_UNIQUEID that has a key length of 8 on each field.
From what I understand, the filesort is kicking in because we're ordering the resulting records in descending order using the primary key (id), and there's no way around that (according to what I've read). Essentially, we simply want the latest record matching the given criteria, but there has to be a better way.
Technically, we will be implementing a new version of this section of code in a couple of months that is FAR more efficient and scalable, but in the meantime, I'm trying to figure out the best way to patch this ship.
Can anyone think of a good solution here? Thanks in advance!
- Jonathan
Start Free Trial