3

我正在尝试返回一个表,其中包含使用嵌套集模型表示的层次结构中的节点深度,我正在关注本教程,但“查找节点深度”部分中使用的查询对我不起作用: http: //mikehillyer.com/articles/managing-hierarchical-data-in-mysql/

SELECT node.GroupName, (COUNT(parent.GroupName) - 1) AS depth
FROM CompanyGroup AS node,
        CompanyGroup AS parent
WHERE node.LeftID BETWEEN parent.LeftID AND parent.RightID
GROUP BY node.GroupName
ORDER BY node.LeftID;

运行此查询我收到错误“列 'CompanyGroup.GroupName' 在选择列表中无效,因为它既不包含在聚合函数或 GROUP BY 子句中。

谁能解释一下为什么?

编辑:错误消息中的错误列,我很抱歉错误是:“列“CompanyGroup.LeftID”无效......

4

3 回答 3

5

试试这个——

SELECT 
      node.GroupName
    , depth = COUNT(parent.GroupName) - 1
FROM CompanyGroup node
JOIN CompanyGroup parent ON node.LeftID BETWEEN parent.LeftID AND parent.RightID
GROUP BY node.GroupName
ORDER BY MIN(node.LeftID) --<--

或者试试这个 -

SELECT 
      node.GroupName
    , depth = COUNT(parent.GroupName) - 1
FROM CompanyGroup node
JOIN CompanyGroup parent ON node.LeftID BETWEEN parent.LeftID AND parent.RightID
GROUP BY node.GroupName, node.LeftID
ORDER BY node.LeftID
于 2013-05-29T12:58:59.917 回答
2

您是否正在运行不同的查询?你不应该收到那个特定的错误,而是像"Column "CompanyGroup.LeftID" is invalid in the ORDER BY..."

此查询应该有效:

SELECT node.GroupName, (COUNT(parent.GroupName) - 1) AS depth
FROM CompanyGroup AS node,
        CompanyGroup AS parent
WHERE node.LeftID BETWEEN parent.LeftID AND parent.RightID
GROUP BY node.GroupName
;
于 2013-05-29T12:59:46.887 回答
0

我不认为这是您从发布的查询中收到的错误 - 您确定您没有搞砸吗?

无论如何,这里还有其他问题:您node.LeftID用于订购结果,但您不能这样做。您应该会收到此消息:

Column "node.LeftID" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause.

尝试删除 ORDER BY 并再次运行它。

于 2013-05-29T13:00:13.983 回答