You could add a where clause that filters out rows for which 4 rows with lower photo_id
's exist:
select *
from YourTable t1
where 4 > (
select count(*)
from YourTable t2
where t1.event_id = t2.event_id
and t1.photo_id < t2.photo_id
)
limit 100
This can get kind of slow for huge tables. A faster, but very MySQL specific option is to use variables. For example:
select *
from (
select
@nr := case
when event_id = @event then @nr + 1
else 1
end as photonr
, @event := event_id
, t1.*
from YourTable as t1
cross join (select @event := -1, @nr := 1) as initvars
order by event_id
) as subquery
where subquery.photonr < 5
limit 100;
Test data used:
drop table if exists YourTable;
create table YourTable (
id int auto_increment primary key
, event_id int
, photo_id int
);
insert into YourTable (event_id, photo_id)
values (1,1), (1,2), (1,3), (1,4), (1,5), (2,1), (1,6);