Say I have the following table giving a relation between oldID and newID, say when the ID of an item is changed.
+-------+-------+
| oldID | newID |
|-------|-------|
| 1 | 2 |
| 2 | 3 |
| 3 | 4 |
| 4 | 5 |
| 7 | 9 |
+-------+-------+
There are three types of queries I need to make:
- Find all "chains of linked IDs", starting from oldest to latest.
- Given some ID, find the chain of IDs in its future.
- Given some ID, find the chain of IDs in its past.
So the first one should ive:
(1, 2), (2, 3), (3, 4), (4, 5)
(7, 9)
In the second example, suppose I give input 3, the output should be:
(3, 4), (4, 5)
The third example should output the following for the same input:
(1, 2), (2, 3)
What is the most efficient way to write the three SQL queries (in a portable manner)?
EDIT:
The results I need are as follows:
Query 1
chainID | chainIndex | ID
-------+------------+----
1 1 1
1 2 2
1 3 3
1 4 4
1 5 5
2 1 7
2 2 9
Query 2: Input 3
itemID
______
3
4
5
Query 3: Input 3
itemID
______
3
2
1
I am more interested in 2 and 3 as I can keep a separate table with the IDs of the head (first element) of each chain and implement 1 via 2. It is guaranteed that each ID has at most one child and parent, and I know the head of each chain.