I need to represent graph information with relational database.
Let’s say, a is connected to b, c, and d.
a -- b |_ c |_ d
I can have a node table for a, b, c, and d, and I can also have a link table (FROM, TO) -> (a,b), (a,c), (a,d).
For other implementation there might be a way to store the link info as (a,b,c,d), but the number of elements in the table is variable.
- Q1 : Is there a way to represent variable elements in a table?
- Q2 : Is there any general way to represent the graph structure using relational database?
I assume you mean something like this?
This is not a good idea. It violates first normal form.
For a directed graph you can use a table
edgeswith two columns:If there is any extra information about each node (such as a node name) this can be stored in another table
nodes.If your graph is undirected you have two choices:
nodeid_frommust be less thannodeid_to(i.e. store 1->2 but 2->1 is implied).The former requires twice the storage space but can make querying easier and faster.