使用关系数据库表示图 [英] representing graph using relational database
问题描述
我需要用关系数据库表示图信息。
I need to represent graph information with relational database.
假设a连接到b,c和d。
Let's say, a is connected to b, c, and d.
a -- b
|_ c
|_ d
我可以拥有a,b,c和d的节点表,也可以拥有链接表(FROM,TO)->(a,b),(a ,c),(a,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:是否可以表示表中的变量元素?
- Q2:是有没有使用关系数据库表示图结构的一般方法?
推荐答案
Q1:有没有一种方法可以表示[数据库]表中的变量元素?
Q1 : Is there a way to represent variable elements in a [database] table?
我假设您的意思是这样的?
I assume you mean something like this?
from | to_1 | to_2 | to_3 | to_4 | to_5 | etc...
1 | 2 | 3 | 4 | NULL | NULL | etc...
这不是一个好主意。它违反了第一范式。
This is not a good idea. It violates first normal form.
第二季度:是否有使用数据库表示图结构的一般方法?
Q2 : Is there any general way to represent the graph structure using database?
对于有向图,可以使用具有两列的表 edges
:
For a directed graph you can use a table edges
with two columns:
nodeid_from nodeid_to
1 2
1 3
1 4
如果有多余的东西有关每个节点的信息(例如节点名称)可以存储在另一个表 nodes
中。
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:
- 存储两个方向(即存储1-> 2和2-> 1)
- 使用一个约束,即
nodeid_from
必须小于nodeid_to
(即商店1-> 2但暗示2-> 1)。
- store both directions (i.e. store 1->2 and 2->1)
- use a constraint that
nodeid_from
must be less thannodeid_to
(i.e. store 1->2 but 2->1 is implied).
前者需要两倍的存储空间,但可以使查询更容易nd。
The former requires twice the storage space but can make querying easier and faster.
这篇关于使用关系数据库表示图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!