MySQL:计算子项并获取父行

时间:2011-03-23 02:53:58

标签: php mysql count group-by

我想计算属于一组父页面的总项目数,并获取父项的行数,例如

pg_id     pg_title      parent_id
1         A             1            
2         B             2
3         C             3
4         d             1
5         e             1
6         f             2
7         g             1
8         k             3
9         l             3
10        j             3

所以我想得到这样的结果,

ParentName    ParentID      TotalCout
A             1             3
B             2             1
C             3             3

这是我到目前为止提出的查询,但它没有返回结果正确,它没有得到父母的页面标题,而是返回他们的子页面标题,

SELECT root_pages.pg_title as ParentName,x.ParentID,x.TotalCount
FROM 
(
SELECT root_pages.parent_id as ParentID, COUNT(root_pages.parent_id) as TotalCount
FROM root_pages
WHERE root_pages.parent_id != root_pages.pg_id
AND root_pages.pg_hide != '1'
GROUP BY root_pages.parent_id
)x

LEFT JOIN root_pages
ON x.ParentID = root_pages.parent_id

GROUP BY x.ParentID

我有什么想法可以得到我需要的正确结果吗?

由于

3 个答案:

答案 0 :(得分:2)

试试这个:

SELECT a.pg_title as ParentName,
             a.pg_id as ParentID,
             b.TotalCout
  FROM root_pages a INNER JOIN
         (
        SELECT parent_id, COUNT(1) as TotalCout
          FROM root_pages
           WHERE parent_id <> pg_id
        GROUP BY parent_id
         ) b 
     ON a.pg_id = b.parent_id
     AND b.TotalCout>0

答案 1 :(得分:2)

select p.pg_title ParentName, p.pg_id ParentID, IFNULL(c.TotalCout,0) TotalCout
from root_pages p
left join
(
    select parent_id, count(*) TotalCout
    from root_pages
    where parent_id != pg_id
    group by parent_id
) c on c.parent_id=p.pg_id
WHERE p.pg_id = p.parent_id

如果您对没有孩子的根(父)页面不感兴趣,请将LEFT JOIN更改为INNER JOIN。

在单个选择中,给定您的数据属性root := (parent_id=pg_id)

select max(case when pg_id=parent_id then pg_title end) ParentName,
       parent_id ParentID,
       count(*)-1 TotalCout
from root_pages
group by parent_id
having count(*) > 1

答案 2 :(得分:0)

我认为你只是加入了错误的领域。尝试加入x.parentid = root_pages.pg_id