问题
How do I calculate a node's depth in a parent-child model under MySQL?
I'll need the depth to, among other things, create the indent in my list (coded with PHP).
回答1:
That depends on the actual implementation of your hierarchy in the database. If you are using nested sets model (http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/) you can retrieve the full parent-to-child path via a single select.
Update: Ok, since you're going with adjacency list model I suggest to store node level in the table. Not only will it give you the node depth in one query, but it will also allow you to retrieve the entire path to that node in one query (albeit that query would have to be dynamically generated):
SELECT n1.name AS lvl1, n2.name as lvl2, n3.name as lvl3, ..., nN.name as lvlN
FROM nodes AS n1
JOIN nodes AS n2 ON n2.parent_id = n1.id
JOIN nodes AS n3 ON n3.parent_id = n2.id
...
JOIN nodes AS nN ON nN.parent_id = n(N-1).id
WHERE nN.id = myChildNode;
Since you know that your node is on level N there's no need for left joins and, given appropriate indexes on id / parent_id this should be reasonably fast.
The downside to this approach is that you'll have to keep node level updated during node moves, but that should be reasonably straightforward and fast as you would only do it for the node itself and its children - not for the majority of the table as you would do with nested sets.
回答2:
This might be an old question, but I just want to let others know that I found a solution some months ago. I did recently write about it here: http://en.someotherdeveloper.com/articles/adjacency-list-model-with-depth-calculation/
回答3:
If you want just to copy paste here is my example. I have table Projects with ID and PARENT_ID fileds.
DELIMITER $$
DROP FUNCTION IF EXISTS `getDepth` $$
CREATE FUNCTION `getDepth` (project_id INT) RETURNS int
BEGIN
DECLARE depth INT;
SET depth=1;
WHILE project_id > 0 DO
SELECT IFNULL(parent_id,-1)
INTO project_id
FROM ( SELECT parent_id FROM Projects WHERE id = project_id) t;
IF project_id > 0 THEN
SET depth = depth + 1;
END IF;
END WHILE;
RETURN depth;
END $$
DELIMITER ;
来源:https://stackoverflow.com/questions/1195863/calculate-depth-in-a-parent-child-model-in-mysql