请参阅http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/
在“嵌套集合中的聚合函数”标题下
我正在尝试找出类似于给定示例的查询,除了我希望它在子树级别工作,所以如果我查询MP3播放器,我会得到一个结果集,如;
|NAME |COUNT|
----------------------
|MP3 PLAYERS | 2 | // 2 because 1 at this level and 1 at child level
|FLASH PLAYERS | 1 |
答案 0 :(得分:0)
假设自引用表tree_node按如下方式创建:
CREATE TABLE tree_node
(
id serial NOT NULL,
parent integer,
"desc" text,
l integer,
r integer,
CONSTRAINT tree_node_pkey PRIMARY KEY (id)
);
可以使用以下SQL检索计数:
select count(*), p.id, p.desc from tree_node c, tree_node p
where c.l<=p.r
and c.l>=p.l
group by p.id, p.desc;