I have a SQL table that represents a relationship between two accounts like the following:
+---+---+
| a | b |
+---+---+
| 1 | 2 |
| 2 | 3 |
| 1 | 4 |
| 3 | 4 |
| 4 | 1 |
+---+---+
Columns a
and b
are the two sides of the relationship such that (i
, j
) represents a bidirectional relationship between account i
and j
. The preconditions for this table are the following:
a
will never equalb
, i.e.a
=/=b
- As the relationships are bidirectional, if there's a relationship (1, 2) there won't be another (2, 1) tuple in the table.
- Columns
a
andb
are primary keys.
For example:
+---+---+
| a | b |
+---+---+
| 1 | 2 |
| 2 | 3 |
| 1 | 4 |
| 2 | 2 | <- Will never happen
| 3 | 4 |
| 4 | 3 | <- Will never happen, same as previous row
+---+---+
With that said, I'm implementing a feature where relationships are transitive, i.e., if there's a relationship (1, 2) and another (2, 3), then there must be an implicit relationship (1, 3).
I'm trying to find a way to do this without having to modify the schema. I would probably be able to code this doing multiple SQL queries but I don't think that would be very efficient, so I'm looking for a way to do this with only one query that allows me for user 1, get all accounts related to them.
For example, in the first example, for account 1 I would expect the result [2, 3, 4]. Any idea on how to accomplish this?