I am trying to join three tables - one parent table and two children table. However, joining creates multiple combinations appear in result set hence increasing the number of rows exponentially.
parent_operations_table:
id | name |
---|---|
1 | Operation_101 |
2 | Operation_102 |
child_task_table:
id | name | parent_id |
---|---|---|
1 | Task_1_Operation_101 | 1 |
2 | Task_2_Operation_101 | 1 |
child_review_table:
id | name | parent_id |
---|---|---|
1 | Review_1_Operation_101 | 1 |
2 | Review_2_Operation_101 | 1 |
My desired table is like this
id | name | task_id | review_id |
---|---|---|---|
1 | Operation_101 | 1 | 1 |
1 | Operation_101 | 2 | 2 |
2 | Operation_102 | null | null |
And the table which I am getting is like this:
id | name | task_id | review_id |
---|---|---|---|
1 | Operation_101 | 1 | 1 |
1 | Operation_101 | 1 | 2 |
1 | Operation_101 | 2 | 1 |
1 | Operation_101 | 2 | 2 |
2 | Operation_102 | null | null |
Currently I am just joining and not aggregating over anything and selecting distinct, but as we can see every row is actually a distinct row by itself. I am using left joins as we can see for Operation #2 that operations may not have any tasks or reviews defined at some given point of time. I felt using aggregation such as MAX to ignore the nulls is not possible as well, as it will also take max of the child IDs grouping by parent_id. And I don't want to turn it into a comma separated aggregation as well. If anyone has faced this issue and knows a workaround any help would be greatly appreciated. Thanks!
Edit: adding query used - just 2 left joins
SELECT op.id, ts.task_id, rvw.review_id
FROM operations op
LEFT JOIN tasks ts ON op.id=ts.parent_id
LEFT JOIN reviews rvw ON op.id=rvw.parent_id
http://sqlfiddle.com/#!18/4cb2f5/2 - Please find the sample at this link