简体   繁体   中英

Traversing directed cyclic graph in SQLite on Android

Say I have two SQL tables: NODES and EDGES Nodes contains information pertaining to each node, and each row in EDGES contains a directed edge between two nodes.

ie

Table EDGES  
|edge_id | node_from_id | node_to_id |
|      1 |            1 |          2 |
|      2 |            1 |          3 |
|      3 |            2 |          1 |
|      4 |            3 |          5 |
|      5 |            6 |         10 |
|      6 |            6 |         11 |
|      7 |            7 |          8 |

Querying the table for all the children of a node is trivial, but what if I want to have a list of all the children of all the children of a node? Or better yet a list of all the edges that create a tree of the node's descendants? Note that the graph may be cyclical and is not fully connected.

For example, I want to select all the descendant edges of node 1:

QUERY Results:
|edge_id | node_from_id | node_to_id |
|      1 |            1 |          2 |
|      2 |            1 |          3 |
|      3 |            2 |          1 |
|      4 |            3 |          5 |

In SQL and SQLite 3.8.3+ I could use something like a Common Table Expression (CTE) to do this and there are many answers on SO to that effect. But on Android I'm currently limited to SQLite 3.4.0 which doesn't support CTE's.

I could programmatically query each level of the tree, but I would prefer to do this all in SQL if possible. Is there a neat way to accomplish this given my limitations?

CTEs exists because there is no other way to do recursive queries.

You have to query the children step by step.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM