Q:

Getting first N rows between 2 timestamps for each ID Mysql

I have table like below, start_t is my timestamp in unixtime for example (1438326239412) but for simplicity I wrote small numbers here:
user_id | start_t | duration
1         12           1
1         15           2
1         4            5
2         9            6
2         10           5
3         9            6       

I want to get first N rows for each user_id between two time stamps. This is my code but it returns more than the limit I want:
SELECT us.* FROM (SELECT us.*, (@rn := if(@i = us.user_id, @rn + 1, if(@i := us.user_id, 1, 1) ) ) AS seqnum FROM user_stats us,tourn_user tu CROSS JOIN (SELECT @rn := 0, @i := -1) params WHERE (us.start_t+us.duration)<= 20 AND us.start_t >= 4 ORDER BY us.user_id, start_t ASC ) us WHERE seqnum <= 1

The result should look like this for that specific example:
user_id | start_t | duration
1         4            5
2         9            6
3         9            6       

A:

Here is the solution in case someone wants:
select us.* from (select us.*, (@rn := if(@i = us.user_id, @rn + 1, if(@i := us.user_id, 1, 1) ) ) as seqnum from user_stats us cross join (select @rn := 0, @i := -1) params where (us.start_t+us.duration)<= 15 AND us.start_t >= 0 order by us.user_id, start_t ASC ) us where seqnum <= 1 

