如何限制提取的子行仅为5?
这是SQLfiddle http://sqlfiddle.com/#!2/bd96a/2。现在,它使用parentid='4'
和parentid='14'
获取所有行。它应该只取每个parentid 5。假设我有数百行,每个parentid
最多只能获取5个。
"SELECT child.* FROM mytable as parent
LEFT JOIN mytable as child on child.parentid=parent.id
WHERE parent.pageid IN ( 1, 2) AND parent.submittype='1'
ORDER BY child.id ASC";
我如何解决这个问题?
答案 0 :(得分:1)
你想要每组最大的n ..这将做你想要的。抱歉,我在手机上,所以我无法对其进行格式化。如果有人可以为我编辑那就太棒了!
SELECT
child.*,
if(@a = child.parentid, @b :=@b+1, @b := 1) as counting_col,
@a := child.parentid
FROM mytable as parent
LEFT JOIN mytable as child on child.parentid=parent.id
CROSS JOIN(select @a :=0, @b:=1) t
WHERE parent.pageid IN ( 1, 2)
AND parent.submittype='1'
HAVING counting_col <=5
ORDER BY child.id ASC