SQLite Forum

Find the relation in a sql query
Login
The SQLite documentation contains an example of [traversing a tree structure][1] , which is much like your requirement. 

Not exactly the same, but close enough to inspire you.

[1]: https://www.sqlite.org/lang_with.html#controlling_depth_first_versus_breadth_first_search_of_a_tree_using_order_by