所以,我有一个父表,它有子记录,同时有详细信息(3级父母表)。我需要获取父名称,以及他们各自的子项和children_detail COUNTs。
父
的子
children_detail
直到第二级:
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中获得第三级计数?谢谢!
答案 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
如果所有其他方法都失败了,你可以使用两个子查询(非常糟糕的做法,但对于你的大小的表格应该没问题):
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