MySQL nested set non-children relationships
-
19-06-2021 - |
Question
I have a nested set of organisations, that looks something like this (the nodes are org ids):
1234 is a parent of 4499 and 3322, but 9905 is "affiliated", not really a parent or child, to 1234.
I believe that the leftedge, rightedge set up should look something like:
orgID | leftedge | rightedge
1234 | 1 | 6
4499 | 2 | 3
3322 | 4 | 5
9905 | 7 | 8
Since 9905 isn't really a Child of 1234, i'm not sure how i can get the relationship between 1234 and 9905. The SQL i use to get child relationships is:
SELECT ost.orgid, ost.leftedge, ost.rightedge
FROM tbl_organisationsettree ost
JOIN tbl_organisationsettree AS child_ost ON child_ost.leftedge BETWEEN ost.leftedge AND ost.rightedge
AND child_ost.supersetid = ost.supersetid
WHERE 1
AND ost.leftedge > 1
AND ost.rightedge <6
GROUP BY child_ost.ID
HAVING COUNT(child_ost.ID) = 1
Solution
Finds any node that is not descedant or ancestor of node 1234
:
SELECT ost.* --- whatever from `org` table
FROM tbl_organisationsettree AS ost
JOIN tbl_organisationsettree AS param
ON param.leftedge NOT BETWEEN ost.leftedge
AND ost.rightedge
AND ost.leftedge NOT BETWEEN param.leftedge
AND param.rightedge
WHERE param.orgID = 1234
--- if you only root nodes:
---
--- AND NOT EXISTS
--- ( SELECT *
--- FROM tbl_organisationsettree AS parent
--- WHERE ost.leftedge > parent.leftedge
--- AND ost.leftedge < parent.rightedge
--- )
;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow