As said in the comments, there is no shortcut with mysql.
BUT!
If you have the opportunity to change the structure of the database, you can deploy the best design for processing tree hierarchies.
If you follow THIS tutorial from Bill Carwin ( HERE is the original answer that refers to the slideshow tutorial), you can find 4 methods used to model the hierarchical structure:
- List of indicators>
- Enumeration path
- Nested Kits
- Closing table
Now the best model possible is the fourth (I leave the reader with descriptions of the other 3 models), which basically needs 2 tables: one for the elements and one for the paths. In the path table (the closure table itself), you will store every path from each node to each descendant (and not just from direct children!).
He suggested that you also keep the path length for each row, as it simplifies the query for immediate children in the tree.
Even if this solution requires more space, it has better overall performance and is very easy to use: it does not rely on recursive queries at all. And it will provide referential integrity for the entire dataset!
For example, to get each child device node # 4:
select a.* from nodes a join paths b on a.node_id = b.descendant where b.ancestor = 4
Another example: get all node # 11 ancestors
select a.* from nodes a join paths b on a.node_id = b.ancestor where b.descendant = 11
need to remove subtree <node # 6
delete from paths where descendant in (select descendant from paths where ancestor = 6)
source share