I am having trouble debugging a slow query, when I take it appart they perform relatively fast, let me break it down for you:
The first query, which is my subquery, groups all rows by lmu_id
(currently only 2 unique ones) and returns the max(id)
in other words the last inserted row.
SELECT max(id) FROM `position` GROUP by lmu_id
-> 15055,15091
2 total, Query took 0.0030 seconds
The outer query retrieves the full row of those two positions, so here I've manually inserted the ids (15055,15091)
SELECT * FROM `position` WHERE id IN (15055,15091)
2 total, Query took 0.1169 sec
Not the fastest query, but still a bink of an eye.
Now my problem is I do not understand why if I combine these two queries the whole system crashes:
SELECT * FROM `position` AS p1 WHERE p1.id IN (SELECT max(id) FROM `position` AS p2 GROUP by p2.lmu_id)
takes forever, 100% cpu, crashing, lost patience after 2 minutes, service mysql restart
For your reference I did an explain of the query
EXPLAIN SELECT * FROM `position` AS p1 WHERE p1.id IN (SELECT max(p2.id) FROM `position` AS p2 GROUP by p2.lmu_id)
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY p1 ALL NULL NULL NULL NULL 7613 Using where
2 DEPENDENT SUBQUERY p2 index NULL position_lmu_id_index 5 NULL 1268 Using index
id
is the primary key, and lmu_id
is a foreign key and also indexed.
I'm really stumped. Why is the final query taking so long/crashing? What other things shoud I look in to?