计数嵌套设置子项

时间:2014-12-13 02:17:05

标签: sql nested-sets

我创造了以下小提琴: http://sqlfiddle.com/#!2/fc0d9/19

我试图通过调整以下SQL来计算每个节点的直接子节点数: http://en.wikipedia.org/wiki/Nested_set_model

CREATE TABLE Personnel 
    (
     name varchar(20), 
     lft int,
     rgt int
    );

SELECT Parent.name, count(Child.*)
FROM Personnel AS Child, Personnel AS Parent 
WHERE Parent.lft < Child.lft AND Parent.rgt > Child.rgt
GROUP BY Parent.name

1 个答案:

答案 0 :(得分:3)

以下修复了语法错误:

SELECT Parent.name, count(*)
FROM Personnel AS Child join
     Personnel AS Parent 
     on Parent.lft < Child.lft AND Parent.rgt > Child.rgt  -- associate Child Nodes with ancestors
GROUP BY Parent.name;

SQL不允许使用表达式count(child.*)