For example given this table
id | category
1 | 10
2 | 10
3 | 10
4 | 10
5 | 20
6 | 20
7 | 20
8 | 30
9 | 30
10 | 30
11 | 30
We want obtain first 2 small id, from each category, that is we need this result
1
2
5
6
8
9
I wriite this query and his works
SELECT MIN(id) AS id FROM mytable GROUP BY category
UNION
SELECT MIN(id) AS id FROM mytable WHERE
id NOT IN (SELECT MIN(id) AS id FROM mytable GROUP BY category) GROUP BY category
ORDER BY id
but here is one problem, this works if we want first 2 id from each category, but if we want more first small ids (for example 7) from each category, query will be very difficult.
Someone has idea, how can make this easy?
@Quassnoi wrote a couple of very informative blog articles on this subject, concluding that the following would be extremely performant if you have a composite index on
(category, id):See it on sqlfiddle.
To select the first 4 records, change
LIMIT 1,1toLIMIT 3,1. More generally: to select the first n records, changeLIMIT 1,1toLIMIT n-1,1.