There is no reason to reinvent a wheel and risk you have a buggy, suboptimal code. Your problem is trivial extension of common per group limit problem. There are already tested and optimized solutions to solve this problem, and from this resource I would recommend to choose from following two solutions. These queries produce latest 30 records for each player (rewritten for your tables):
select user_id, points
from players
where (
select count(*) from players as p
where p.user_id = players.user_id and p.player_id >= players.player_id
) <= 30;
(Just to make sure I understand your structure: I suppose player_id
is a unique key in players table and that one user can be present in this table as multiple players.)
Second tested and optimized solution is to use MySQL variables:
set @num := 0, @user_id := -1;
select user_id, points,
@num := if(@user_id = user_id, @num + 1, 1) as row_number,
@user_id := user_id as dummy
from players force index(user_id) /* optimization */
group by user_id, points, player_id /* player_id should be necessary here */
having row_number <= 30;
The first query will not be as optimial (is quadratic), while the second query is optimal (one-pass), but will only work in MySQL. The choice is up to you. If you go for the second technique, beware and test it properly with your keys and database setting; they suggest in some circumstances it might stop working.
Your final query is trivial:
select user_id, avg(points)
from ( /* here goes one of the above solutions;
the "set" commands should go before this big query */ ) as t
group by user_id
Note that I have not incorporated the condition you have in your 1st query (points != 0)
as I don't understand your requirement well (you haven't described it), and I also think this answer should be general enough to help others with similar problem.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…