繁体   English   中英

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

[英]Column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

我正在尝试返回一个表格,其中包含使用嵌套集合模型表示的层次结构中的节点深度,我正在遵循本教程,但“查找节点深度”一节中使用的查询对我不起作用: 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;

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

谁能解释为什么好吗?

编辑:错误消息中的列错误,我的道歉错误是:“ Column”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

你在运行不同的查询吗? 您不应该收到该特定错误,而是像"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
;

我不认为这是你从你发布的查询中收到的错误 - 你确定你没有弄乱它吗?

无论如何,这里还有其他错误:你使用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并再次运行它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM