Sunday, 8 September 2013

Find all nodes within a subtree that has 0 or 1 children

Find all nodes within a subtree that has 0 or 1 children

In something I need to work on, at a given time, I need to find all nodes
of a tree (made using the materialized path + adjacent nodes) that have 0
or 1 children. The columns are something like:
id int
parent_node int
treepath VARCHAR(255)
deepness int
When I try to come up with a solution to this, I'm only able to think of
very complex queries that would use too many subqueries or table joins.
For the nodes with 0 children, I've been thinking of searching for all
nodes that are not referenced by a parent_id and are within a subtree.
SELECT *
FROM user_tree
WHERE
node_id NOT IN (
SELECT parent_id
FROM user_tree
WHERE parent_id IS NOT NULL
)
AND
treepath LIKE
(
SELECT CONCAT(treepath, '/%')
FROM user_tree
WHERE node_id = 4
)
Using the EXPLAIN, this seems to be kinda painful for the DB in therms of
how long it takes to get the node list.
Is there a non-very-painful way (in performance) to make a query that
finds what I want?

No comments:

Post a Comment