I'm running a website that allows users to scrape and analyse their Instagram competitors / personal accounts, to monitor their growth and see how things are going and if they're on track with their growth targets.
For this specific portion of the website, one of my MySQL queries has been running really slow (4-6s each time).
I have two tables : - myaccounts (stores all the accounts each user is tracking) - accounts (stores all the raw data. Each account is scanned every 2 hours and a new record is added in here)
Here is the query that is running really slow:
SELECT M.type, M.status, M.id as masterid, A.*
FROM myaccounts as M
INNER JOIN accounts as A on M.accountid = A.userid
WHERE A.id = (
SELECT MAX(id)
FROM accounts
WHERE userid = M.accountid)
AND M.userid = ?
AND M.status = 'active'
Using an EXPLAIN reveals that the subquery is actually going through every single row in the table (about 180k so far).
The reason I'm using MAX(id) is I want to display the very latest data for the accounts on the home page and give the option for users to access all the raw data on a another page.
Is there any way to speed this up? Some sort of INDEX on MAX()?
Thanks! :)
Mark