I ran into an issue with Postgres 9.3+ and I'm stuck somehow. I have the following structure:
The task is to translate a specific object into another object (basically to answer a question like "who belongs this invoice to?").
The objects are identified by an ID and the possible translations are stored in a table like this:
vagrant=# select * from sys_context_translation;
source_context | target_context | sys_service_id
----------------+----------------+----------------
1 | 2 | 1
3 | 2 | 2
2 | 1 | 1
1 | 4 | 1
4 | 5 | 2
4 | 2 | 3
(6 rows)
As you see, there is a path from 3 to 5 going like 3 - 2 - 1 - 4 - 5.
I need now a query which shows me that path. (so 1 row for source_context 3, next one for 2, next one for 1, and so on...). I have the following query right now but it doesn't return the required result:
WITH RECURSIVE translation (source_context, target_context, sys_service_id)
AS
(
SELECT
source_context,
target_context,
sys_service_id
FROM sys_context_translation AS s1
WHERE source_context = 3
UNION ALL
SELECT
s2.source_context,
s2.target_context,
s2.sys_service_id
FROM sys_context_translation AS s2, translation AS t1
WHERE t1.target_context = s2.source_context
) SELECT *
FROM translation
;
It does return a lot, but then keeps returning the rows. Example below limited to 10 rows.
source_context | target_context | sys_service_id
----------------+----------------+----------------
3 | 2 | 2 (good one)
2 | 1 | 1 (good one)
1 | 2 | 1 (not useful)
1 | 4 | 1 (good one)
2 | 1 | 1 (not useful)
4 | 5 | 2 (good one)
4 | 2 | 3 (should have stopped a row before)
1 | 2 | 1 (...)
2 | 1 | 1
1 | 4 | 1
(10 rows)
I am very thankful for any hint.