我有带有数据的表:并且为此表我需要按productId列创建钉书钉。我知道LIMIT N,M,但它适用于行而不适用于组。例如,我的表的桩号= 2,我希望检索productId = 1和2(组数为2)的所有9条记录。
那么,如何通过组数创建钉书钉呢?
我将非常感谢您提供示例答案。
按组进行分页的一种方法是为查询分配产品序列。使用变量,这需要一个子查询:
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;
启用索引后t(productid)
,您也可以使用子查询来执行此操作。然后,该条件可以放在having
子句中:
select t.*,
(select count(distinct productid)
from t t2
where t2.productid <= t.productid)
) as pno
from t
having pno between X and Y;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句