Tree Database View Query (MySQL)

I have two tables, one of which contains nodes and the second, which contains the relationships between them:

Table A (named Node)

NodeID | NodeName 
 100   |  Name 1
 101   |  Name 2
 102   |  Name 3

Table B (named relationship)

NodeParent | NodeChild
  100      |    101
  101      |    102

I need to execute a query that needs to find which nodes are orphans (they are not in the relationship table). How can I search through NodeParent and NodeChild at the same time?

+1
source share
2 answers
SELECT 
  n.NodeID 
FROM 
  Node AS n 
LEFT JOIN 
  Relationship AS r
ON
  n.NodeID = r.NodeChild
WHERE
  r.NodeChild IS NULL
+2
source

This will give you all nodes that do not have children in the relationship table.

select n.*
from Node n
left join Relationship r on r.NodeChild = n.NodeID
where r.NodeChild is null;
+1
source

Source: https://habr.com/ru/post/1794486/


All Articles