I want to store undirected graph edges (for example, for friends). To store and retrieve all friends of node a
, one can use:
Create two rows per edge, query on one column per node:
+--------------------------+
| id | from_node | to_node |
+--------------------------+
| 1 | a | b |
| 2 | b | a |
+--------------------------+
SELECT * FROM `x` WHERE from_node = a
Create one row per edge, use OR
:
+--------------------------+
| id | node_a | node_b |
+--------------------------+
| 1 | a | b |
+--------------------------+
SELECT * FROM `y` WHERE node_a = a OR node_b = a
Which makes for more efficient lookups?
- Table
x
with2n
rows, indices onfrom_node
andto_node
, lookup on one column - Table
y
withn
rows, indices onnode_a
andnode_b
, lookup on both columns usingOR