带有join和WHERE子句的子查询

时间:2014-08-23 14:55:19

标签: mysql greatest-n-per-group

我有一个包含25个父行和42个子行的mysql表。子行具有列parent_id,即父行的id。我只选择category='general'的父行,但我只想要这些特定父行的5个子行。

以下是我在下面尝试的但不起作用的查询

 SELECT child.*,parent.title as ptitle FROM 
  (SELECT * FROM mytable WHERE category='general' LIMIT 10) as parent
  LEFT JOIN
  (SELECT * FROM mytable WHERE `parent_id`=parent.id LIMIT 5) as child on child.`parent_id`=parent.id
  ORDER by parent.id ASC

我只想为每个父行获取child.parent_id=parent.id的5个子行。

我是否删除了第二个子查询WHERE子句,因为ON子句负责这个?

如果没有,我如何更改第二个子查询WHERE子句来完成此操作?

1 个答案:

答案 0 :(得分:0)

SELECT id, name, parentid, category 
FROM
(   SELECT child.*, 
           IF(@a = child.parentid, @b:=@b+1, @b:=1) as counting_col, 
           @a := parent.id 
    FROM 
    (   SELECT * 
        FROM mytable 
        WHERE category='general' 
        LIMIT 10
    ) as parent
    LEFT JOIN mytable child ON child.parentid=parent.id
    CROSS JOIN(SELECT @a :=0, @b:=1) t
    HAVING counting_col <=5
    ORDER by parent.id, child.id ASC
)t1;

DEMO