2010-08-02 59 views
3

我在SQLite3数据库中有一个简单的类别层次结构,每行存储一个父ID或NULL(视情况而定)。计算层次结构中直接子项的数量

我想知道一个特定的类是否是一个叶,主要是通过为每一行确定它是否具有定义的父ID。或者,确定每行的子行数。


表定义:

CREATE TABLE category (
    id INTEGER PRIMARY KEY AUTOINCREMENT 
    name TEXT NOT NULL 
    parent_id INTEGER DEFAULT NULL 
); 

的样本数据:

 
id   name  parent_id 
---------- ---------- ---------- 
34   People  
35   Countries 
36   USA   35 
37   Pop   36 
38   Rock  36 
39   Japan  35 
40   Pop   39 
42   Rock  39 
43   J-Pop  40 

所需的输出:
原始数据加多少子类的计数(儿童游乐n)每一行都有。

 
id   name  parent_id direct_children 
---------- ---------- ---------- --------------- 
34   People     0 
35   Countries    2 
36   USA   35   2 
37   Pop   36   0 
38   Rock  36   0 
39   Japan  35   2 
40   Pop   39   1 
42   Rock  39   0 
43   J-Pop  40   0 

这似乎原本很简单的(?),但我通常失去超越了简单的连接,我至今都没有得到很远,与此有关。我已经检查过类似的问题,但是他们似乎要加入表格中,或者想要对整个层次结构中的所有儿童进行更复杂的计数,而不仅仅是直接的儿童行。

更改表格模式是一种可能性(例如,如果child_id或child_count)是必要的,但我宁愿不要。

任何输入将不胜感激。

回答

3

你也许可以做到这一点与子查询:

select c.* 
,  (select count(*) from category c2 where c2.parent_id = c.id) 
      as direct_children 
from category c 

或连接:

select parent.id 
,  parent.name 
,  parent.parent_id 
,  count(child.id) as direct_children 
from category parent 
left join  
     category child 
on  child.parent_id = parent.id 
group by 
     parent.id 
,  parent.name 
,  parent.parent_id 
+0

啊,作为一个子查询简单!这两个在SQLite中都很好用。非常感谢。 – 2010-08-02 13:12:45