问题
I'm trying to return a table with the depth of a node in a hierarchy represented using the nested set model, I'm following this tutorial but the query used in the section 'Finding the depth of Nodes' doesn't work for me: 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;
Running this query I get the error "Column 'CompanyGroup.GroupName' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause."
Can anyone explain why please?
Edit: wrong column in the error message, my apologies the error is: "Column "CompanyGroup.LeftID" is invalid..."
回答1:
Try this one -
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) --<--
Or try this -
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
回答2:
Are you running a different query? You should not be receiving that particular error, but rather something like "Column "CompanyGroup.LeftID" is invalid in the ORDER BY..."
This query should work:
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
;
- SQL Fiddle Demo
回答3:
I don't think that this is the error you're receiving from the query you posted - are you sure you didn't mess it up?
Anyway, there's something else wrong here: you're using node.LeftID to order the results, but you can't od this. You should be receiving this message:
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.
Try removing ORDER BY and run it again.
来源:https://stackoverflow.com/questions/16814343/column-is-invalid-in-the-select-list-because-it-is-not-contained-in-either-an-ag