mysql select语句结果限制

时间:2011-10-05 14:45:11

标签: mysql select nested limit

我有疑问:

select id, name from categories where parent_id in (
    select id 
    from categories 
    where top_main_place > 0
)

它选择父节点的子信息(外部选择)(内部选择)

问题是:我不需要拥有所有子节点数据,每个父id

最多 6 子节点数据

我怎样才能达到这个结果?

顺便说一句,抱歉我的英语很差

3 个答案:

答案 0 :(得分:2)

您应该按parent_id排序外部查询,为每一行提供一个行号(每当parent_id更改时重置行号),然后过滤掉行号大于6的任何行,例如,查看this question和sql代码。

答案 1 :(得分:1)

此页面显示如何使用SQL的几种方言限制查询返回的结果数:http://www.w3schools.com/sql/sql_top.asp

答案 2 :(得分:1)

select id, name FROM (
    select id, name, IF(@parent_id=parent_id, @count:=@count+1, @count:=0) as count, @parent_id:=parent_id from categories, (select @count:=0, @parent_id:=0) as x where parent_id in (
        select id 
        from categories 
        where top_main_place > 0
    ) order by parent_id
) y where count <= 6;
相关问题