Mysql sql层次结构计数
我有一个名为Parentids of ids的sql表及其父id(其中0表示没有父id),如下所示:Mysql sql层次结构计数,mysql,sql,sum,hierarchy,Mysql,Sql,Sum,Hierarchy,我有一个名为Parentids of ids的sql表及其父id(其中0表示没有父id),如下所示: id | parentid -------------- 1 | 0 2 | 0 3 | 1 4 | 0 5 | 2 6 | 2 7 | 3 8 | 1 从这个表中,我需要一个sql查询来返回一个表,其中包含每个id的子级数,这将导致以下结果: id | childrenCnt -------------- 1 | 2 2 | 2 3
id | parentid
--------------
1 | 0
2 | 0
3 | 1
4 | 0
5 | 2
6 | 2
7 | 3
8 | 1
从这个表中,我需要一个sql查询来返回一个表,其中包含每个id的子级数,这将导致以下结果:
id | childrenCnt
--------------
1 | 2
2 | 2
3 | 1
4 | 0
5 | 0
6 | 0
7 | 0
8 | 0
SELECT p.id,
COUNT(DISTINCT ch.id) AS childrenCnt
FROM Parentids p
LEFT JOIN Parentids ch ON p.id = ch.parentid
GROUP BY p.id;
我有以下sql查询,但它似乎不起作用:
SELECT id
,sum(CASE
WHEN parentid = tid
THEN 1
ELSE 0
END) AS childrenCnt
FROM Parentids
一种方法是使用
左连接和聚合。但是,相关子查询甚至可能工作得更好:
select p.id,
(select count(*)
from parentids p2
where p2.parentid = p.id
) as childrenCnt
from parentids p;
您可以使用parentId上的groupby来执行此操作
只有有子女的成员:
select
parentId,
COUNT(*)
from Parentids
where
parentId <> 0
group by
parentId
您可以按父id对记录进行分组,然后删除id=0的记录(第一行)。因此,请尝试以下代码:
select parentid as id, count(*) as childrenCnt
from Parentids
where id <> 0
group by id
选择parentid作为id,将(*)计数为childrencent
来自parentID
其中id 0
按id分组
您可以使用以下选项:
id | childrenCnt
--------------
1 | 2
2 | 2
3 | 1
4 | 0
5 | 0
6 | 0
7 | 0
8 | 0
SELECT p.id,
COUNT(DISTINCT ch.id) AS childrenCnt
FROM Parentids p
LEFT JOIN Parentids ch ON p.id = ch.parentid
GROUP BY p.id;
它生成您指定的输出
请在您使用的数据库管理系统中标记您的问题。您同时标记了MySQL和SQL Server。“它们不是同一件事。”特林科特编辑。我明白了。