I have some kind of impossible request :).
I have a table where one of the columns is named type. I would like to SELECT 3 records for each type in tha
When the table is large and collection is more unpredictable, the row numbering needs to be ordered by type in the inner query for the side-effecting variables to work.
select id, title, type
from (select id, title, type,
@r := CASE WHEN @g = type THEN @r+1 ELSE 1 END r,
@g := type
from tbl
order by type, title) as x
where row_number <= 3
# order by type, title
Another way to do this without using side effecting variables, if no two records are exactly the same on (title, type, id), is given below. This uses only standard ANSI SQL92 SQL. It may be slower than the above though.
select A.id, A.title, A.type
from tbl A
left join tbl B on
A.title = B.title and
(A.type < B.type or
(A.type = B.type and A.id < A.id))
group by A.id, A.title, A.type
having count(B.title) <= 2