I have the following tables:
Table1
id | entity_id | value |
---|
Table2
- Same structure as Table1
id | entity_id | value |
---|
Table3
source_id | destination_id | entity_id |
---|
Table1
and Table2
are both partitions from the same table and Table3
contains the connections between ids
on that partition's tables.
One simple example
id | entity_id | value | table |
---|---|---|---|
1 | 1 | 1 | table1 |
2 | 2 | 2 | table2 |
source_id | destination_id | entity_id |
---|---|---|
1 | 2 | 1 |
In this example the two records are connected directly but it's possible for them to be connected indirectly for instance:
id | entity_id | value | table |
---|---|---|---|
1 | 1 | 1 | table1 |
2 | 2 | 2 | table2 |
3 | 3 | 3 | tablex |
source_id | destination_id | entity_id |
---|---|---|
1 | 3 | 1 |
3 | 2 | 3 |
In this example, the values on Table1
and Table2
are connected via TableX
and this can go any level deep.
Now I'm trying to do a query that would return in this case the rows from Table1
and Table2
.
I did the following:
WITH RECURSIVE cte AS (
SELECT t1.id, t1.entity_id, t1.value
FROM table1 t1
JOIN table3 t3
ON t1.id = t3.source_id
UNION
SELECT j.id, j.entity_id, j.value
FROM cte j
JOIN table3 t3
ON j.id = t3.source_id
JOIN table2 t2
ON t2.id = t3.destination_id
)
SELECT * FROM cte;
But it's only returning:
1 1 1
instead of or similar (I just need the table1 and table2 data)
1 1 1
2 2 2
Any help is welcome.
Thanks