获取具有子项和子项详细信息计数的父项的MySQL结果

时间:2014-02-15 05:28:10

标签: mysql sql count parent-child children

所以,我有一个父表,它有子记录,同时有详细信息(3级父母表)。我需要获取父名称,以及他们各自的子项和children_detail COUNTs。

  • id_parent
  • 名称

的子

  • id_child
  • id_parent
  • 名称

children_detail

  • id_detail
  • id_child
  • 描述

直到第二级:

SELECT parent.id_parent, parent.name,
COUNT(pos.id_pos) AS q
FROM parent
LEFT JOIN children ON children.id_parent = parent.id_parent
GROUP BY parent.id_parent ORDER BY parent.name

如何在同一个SELECT中获得第三级计数?谢谢!

1 个答案:

答案 0 :(得分:1)

由于您的表格不大,请尝试使用子查询:

SELECT parent.id_parent, parent.name,
COUNT(pos.id_pos) AS q,
(SELECT COUNT(*) FROM children_detail cd WHERE cd.id_child = children.id_child) as cdc
FROM parent
LEFT JOIN children ON children.id_parent = parent.id_parent
GROUP BY parent.id_parent ORDER BY parent.name

修改

抱歉,以下内容也应该有效:

SELECT parent.id_parent, parent.name,
  COUNT(pos.id_pos) AS q,
  COUNT(cdc.id_detail) as cdc
FROM parent
  LEFT JOIN children ON children.id_parent = parent.id_parent
  LEFT JOIN children_detail cdc on cdc.id_child = children.id_child
GROUP BY parent.id_parent, parent.name
ORDER BY parent.name

编辑2

如果所有其他方法都失败了,你可以使用两个子查询(非常糟糕的做法,但对于你的大小的表格应该没问题):

SELECT parent.id_parent, parent.name,
  COUNT(pos.id_pos) AS q,
  (SELECT COUNT(*) FROM children_detail cd WHERE cd.id_child IN (SELECT cc.id_child FROM children cc where cc.id_parent = c.id_parent)) as cdc
FROM parent
  LEFT JOIN children c ON c.id_parent = parent.id_parent
GROUP BY parent.id_parent 
ORDER BY parent.name