我正在尝试将仅5个子行连接到父行。这是查询
SELECT child.* FROM
(SELECT * FROM mytable WHERE category='general' LIMIT 10) as parent
LEFT JOIN
mytable as child on child.parentid=parent.id
ORDER by parent.id ASC
当我只想要5个最大值
时,这将获取特定父行的所有子行这是一个sqlfiddle http://sqlfiddle.com/#!2/7d9e7/2,真正的数据还有很多。
我如何限制所以只显示特定父行的5个子行?现在显示了7个带有parentid 1的子行。我希望每个父行只显示5个子行。
答案 0 :(得分:2)
MySQL中最有效的方法是使用变量枚举行并选择前五个:
SELECT c.*
FROM (SELECT child.*,
(@rn := if(@id = parent.id, @rn + 1,
if(@id := parent.id, 1, 1)
)
) as rn
FROM (SELECT * FROM mytable WHERE category='general' LIMIT 10
) parent LEFT JOIN
mytable child
on child.parentid=parent.id CROSS JOIN
(select @id := -1, @rn := 0) vars
ORDER by parent.id ASC
) c
WHERE rn <= 5;