I have three tables:
Task (ID, TaskDescription)
Schedule (TaskID, ID, DueAt)
Audit (TaskID, TestID)
In Schedule table there is a list of scheduled tasks, and Audit table is for already done tasks. So first there is a row in Schedule, then when this task is done it's removing from Schedule table and added into Audit table.
Tasks table
+----+-----------------+
| ID | TaskDescription |
+----+-----------------+
| 1 | Clean room |
| 2 | Remove trash |
+----+-----------------+
Schedule table
+--------+--------+------------+
| ID | TaskID | DueAt |
+--------+--------+------------+
| 927847 | 1 | 2020-08-01 |
| 777777 | 2 | 2020-08-07 |
+--------+--------+------------+
Audit table
+--------+--------+
| TaskID | TestID |
+--------+--------+
| 1 | 3 |
| 1 | 2 |
| 1 | 1 |
| 2 | 4 |
+--------+--------+
I need to take all planned and already done tasks for one task ID. So for example, what I expect as result:
+---------+-----------------+-------------+----------------+--------+
| Task.ID | TaskDescription | Schedule.ID | Schedule.DueAt | TestID |
+---------+-----------------+-------------+----------------+--------+
| 1 | Clean room | 927847 | 2020-08-01 | NULL |
| 1 | Clean room | NULL | NULL | 3 |
| 1 | Clean room | NULL | NULL | 2 |
| 1 | Clean room | NULL | NULL | 1 |
+---------+-----------------+-------------+----------------+--------+
That means already 3 tasks are done and one is scheduled for 2020-08-01. What i tried:
SELECT
TaskID = t.ID,
t.TaskDescription,
ScheduleID = s.ID,
ScheduleDueAt = s.DueAt,
a.TestID
FROM Task t
LEFT OUTER JOIN Schedule s
ON (s.TaskID = t.ID)
LEFT OUTER JOIN Audit a
ON (a.TaskID = t.ID)
WHERE t.ID = '1'
But of course, I get the wrong result:
+---------+-----------------+-------------+----------------+--------+
| Task.ID | TaskDescription | Schedule.ID | Schedule.DueAt | TestID |
+---------+-----------------+-------------+----------------+--------+
| 1 | Clean room | 927847 | 2020-08-01 | 3 |
| 1 | Clean room | 927847 | 2020-08-01 | 2 |
| 1 | Clean room | 927847 | 2020-08-01 | 1 |
+---------+-----------------+-------------+----------------+--------+
I'm going to use UNION for that but first wanted to ask maybe there is more right way how to do it.