I am trying to manage the retrieval of a node in a nested set model table, not through the unique ID, but through the name (a string), and other nodes within the tree under different parents may be called the same way.
As far as now I used an unique ID to get nodes inside the nested sets:
SELECT
node.name, node.lft, node.rgt
FROM tbl AS parent, tbl AS node
WHERE node.lft BETWEEN parent.lft AND parent.rgt
AND node.id = '{$node_id}'
GROUP BY node.id
Trying to extend this method to a more general way to retrieve the node through its name, I came up with a query containing as much HAVING clauses as the depth of the node to retrieve, checking for the node name and its depth:
SELECT
node.name, node.lft, node.rgt, COUNT(node.id) AS depth
FROM tbl AS parent, tbl AS node
WHERE node.lft BETWEEN parent.lft AND parent.rgt
GROUP BY node.id
HAVING
(node.name = 'myParentName' AND depth = 1)
OR
(node.name = 'myParent2Name' AND depth = 2)
OR
...
# and so on
But it is not perfect: having two nodes with the same name and the same depth, but within different parents, both are retrieved, no matter the hierarchy they belong to.
Example:
ARTICLES
|
+--PHP
| +--the-origins
| +--syntax
+--JS
+--history
+--syntax
In this case, the query above would return either ARTICLES/PHP/syntax or ARTICLES/JS/syntax: a “syntax” node with depth 3, infact, is either under the PHP node or under the JS node.
Is there an effective path to walk, to solve this problem?
I’m not quite sure what you’re trying to do here. Are you trying to access the node with the pathname
ARTICLES/PHP/syntax? If so what you’d need to do would be a self-join for each parent level:ETA re comments: doing direct-child matches in nested set isn’t much fun. You’d have to try to select an intermediate parent row between each joined row. This is the row you don’t want to exist, so you then invert that condition with a null left join. eg.: