I tried this:
SELECT MAX(id) id
FROM location_data l
WHERE l.foo_id = 2;
The result is still MAX(id) for appropriate l.foo_id. There is no need to retrieve foo_id as you already know it before the query.
As soon as I removed GROUP BY
, EXPLAIN started giving this:
mysql> EXPLAIN SELECT MAX(id) id
-> FROM location_data l
-> WHERE l.foo_id = 2\G
*************************** 1. row **********************
id: 1
select_type: SIMPLE
table: NULL
type: NULL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: NULL
Extra: Select tables optimized away
1 row in set (0.00 sec)
It means you have done a query that does nothing more than count the number of rows in a table, and that table is a MyISAM table. MyISAM tables are stored with a separate row count, so to do this query MySQL doesn't need to look at any of the table row data at all. Instead it immediately returns the pre-calculated row count. Hence the table access is ‘optimized away’ and the query is lightning-fast.
Meaning of "Select tables optimized away" in MySQL Explain plan
So, I think, getting rid of GROUP BY will speed up your query.