Reputation: 809
I have the table with data:
And for this table I need to create pegination by productId column. I know about LIMIT N,M, but it works with rows and not with groups. For examle for my table with pegination = 2 I expect to retrieve all 9 records with productId = 1 and 2 (the number of groups is 2).
So how to create pegination by numbers of groups ?
I will be very thankfull for answers with example.
Upvotes: 0
Views: 79
Reputation: 1270191
One way to do pagination by groups is to assign a product sequence to the query. Using variables, this requires a subquery:
select t.*
from (select t.*,
(@rn := if(@p = productid, @rn + 1,
if(@rn := productid, 1, 1)
)
) as rn
from table t cross join
(select @rn := 0, @p := -1) vars
order by t.productid
) t
where rn between X and Y;
With an index on t(productid)
, you can also do this with a subquery. The condition can then go in a having
clause:
select t.*,
(select count(distinct productid)
from t t2
where t2.productid <= t.productid)
) as pno
from t
having pno between X and Y;
Upvotes: 1
Reputation: 11
Try this:
select * from
(select * from <your table> where <your condition> group by <with your group>)
LIMIT number;
Upvotes: 1