简体   繁体   中英

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

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 

Use variables!

SELECT r.*
FROM (SELECT r.*,
             (@rn := if(@m = r.zr_miner_id, @rn + 1,
                        if(@m := r.zr_miner_id, 1, 1)
                       )
             ) as rn
      FROM zec_results r CROSS JOIN
           (SELECT @m := -1, @rn := 0) params
      ORDER BY r.zr_miner_id, r.zr_id DESC
     ) r
WHERE rn <= 24 ;

If you want to put the query into a view, then the above will not work. Performance on your approach might improve with an index on (zr_miner_id, zr_id) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM