How to optimize this query (times out for semi-large tables)
I have a query that takes too long to finish (18 seconds on localhost, but it times out on a real server).
This is the table structure. The table has several thousand rows (will increase over time).
This is the query in question:
SELECT bef.Name, aft.Exp - bef.Exp AS Exp FROM (
SELECT * FROM people WHERE EntryID IN (SELECT Max(EntryID) FROM people GROUP BY Name)
) AS aft
JOIN (
SELECT * FROM people WHERE EntryID IN (SELECT Min(EntryID) FROM people WHERE UpdateID >=1 GROUP BY Name)
) AS bef
ON bef.Name = aft.Name
ORDER BY Exp DESC
It does this:
- Find the earliest entry for each person with UpdateID >= 1
- Find the most recent entry for each person.
- Calculate the difference in Exp between the earliest entry, and the most recent entry for each person
- Order that list by Exp, descending
Example:
EDIT: This is the plan it comes up with (idk how to interpret this).
Posted Jul 12, 2018, 12:13 PM UTC · edited
Too many moving pieces to be optimized adequately. Break it out into different queries, each of which can be run optimally by the engine. Yes, multiple hits to the engine will be necessary. Beats the **** out of getting no response at all due to timeout.
Do you have any advice on how to go about doing this? I'm pretty new to SQL. (This query alone took an hour of googling)
What is your programming language of choice (PHP, Ruby, C#, Java, etc)? Each of those has a way of running a query and throwing the results into an array or object. Split your subqueries (everything inside those layers of nested parentheses) out into separate queries.
I'm using PHP. This is the code I'm using:
Which results in this table.
https://pastebin.com/DXMfArSt