当前位置: 首页 > 面试题库 >

该列在选择列表中无效,因为该列未包含在聚合函数或GROUP BY子句中

毋胜涝
2023-03-14
问题内容

我正在尝试返回一个表格,其中包含使用嵌套集模型表示的层次结构中节点的深度,我正在按照本教程进行操作,但是“查找节点的深度”部分中使用的查询对我不起作用: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”无效…


问题答案:

试试这个-

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


 类似资料: