I have a main table and some sub-tables that contain at least 1 column from the main table. Sub-tables are updates of some part of main table. I would like to get updated row of main table at a specific date.
Main table:
table1
| id | colA | colB | colC | colD | colE | createDate |
|:---|:----:|:----:|:----:|:----:|:----:|:-----------:|
| a1 | 1 | 1 | 1 | 1 | 1 | 2017/01/01 |
Sub-tables :
table2
| mainid | colA | colB | createdate |
|:------:|:----:|:----:|:-----------:|
| a1 | 2 | 2 | 2018/05/01 |
| a1 | 3 | 3 | 2019/01/01 |
| a1 | 4 | 4 | 2020/01/01 |
table3
| mainid | colA | colB | colC | createDate |
|:------:|:----:|:----:|:----:|:-----------:|
| a1 | 6 | 6 | 6 | 2019/01/01 |
| a1 | 7 | 7 | 7 | 2020/01/01 |
| a1 | 8 | 8 | 8 | 2021/01/01 |
table4
| mainid | colA | colE | colC | createDate |
|:------:|:----:|:----:|:----:|:-----------:|
| a1 | 9 | 9 | 9 | 2018/06/01 |
| a1 | 10 | 10 | 10 | 2017/01/01 |
| a1 | 12 | 12 | 12 | 2020/01/01 |
I get rows from each table by following code:
select * from table2 where createDate < '2018-07-01' and mainid='a1' order by createDate desc limit 1;
select * from table3 where createDate < '2018-07-01' and mainid='a1' order by createDate desc limit 1;
select * from table4 where createDate < '2018-07-01' and mainid='a1 'order by createDate desc limit 1;
select * from table1 where id = 'a1';
Now I want to combine these rows with the main table's row. If there are multiple values from different tables for 1 specific column, it should use the latest row like this:
table1 -> colD: 1
table2 -> colB: 2
table3 -> nothing
table4 -> colA: 9, colC: 9, colE: 9
selected row :
| id | colA | colB | colC | colD | colE |filteredDate |
|:---|:----:|:----:|:----:|:----:|:----:|:-----------:|
| a1 | 9 | 2 | 9 | 1 | 9 | 2018/07/01 |
How can I get this done in one query? Is this possible? Should I try it in a different way?