SQL query to select last X entries for a certain non-primary field

Viewed 84

I'm having difficulties setting up a slightly more advanced SQL query. What I'm trying to do is to select the last 24 entries for every zr_miner_id, but I keep getting SQL timeouts (the table has around 40000 entries so far). So let's say there's 200 entries for zr_miner_id 1 and 200 for zr_miner_id 2, I'd end up with 48 results.

So far, I've come up with the query below. What this is supposed to do is to select each result in zec_results that has less than 24 newer entries with the same zr_miner_id. I couldn't think of any better way to perform this task, but then again, I'm not that far advanced at SQL yet.

SELECT results_a.*
FROM   zec_results results_a 
WHERE  (
    SELECT COUNT(results_b.zr_id) 
    FROM   zec_results AS results_b 
    WHERE  results_b.zr_miner_id = results_a.zr_miner_id 
    AND    results_b.zr_id >= results_a.zr_id
) <= 24 
1 Answers
Related