Product of two querysets with a parameter in where clause of second result So I have a query that returns a row of some columns.

SELECT a.id, related_a_id FROM tableA


And I have an aggregated query which'd be using each of the rows.

SELECT tc.c_field1 AS cf1, SUM(td.c_field3) AS cf3 FROM tableA ta
   INNER JOIN tableC tc ON ta.id = tc.a_id 
   INNER JOIN tableD td ON tc.d_id = td.id
WHERE ta.id IN (a.id, related_a_id)
GROUP BY cf1


I want to get all the rows for the second query for each pair from the first query with a resulting queryset columns including a_id, related_a_id, cf1, cf3.

Sample data and my attempts are available at this sql-fiddle.
Here is the query that can be used to get desired result

select ta.id,ta.related_a_id,tc.c_field1 as cf1,sum(td.c_field3) as cf3
from tableA ta
inner join tablec tc on tc.a_id in (ta.id,ta.related_a_id)
inner join tabled td on td.id = tc.d_id
group by cf1, ta.id order by ta.id;