I have multiple queries in the following format:
Query 1:
Select id,first_name,middle_name
from table1
where id < 4
Output 1:
id | first_name | middle_name |
---|---|---|
1 | Linda | Marie |
2 | Mary | Alice |
3 | John | Steven |
Query 2:
Select id,last_name
from table2
where id < 4
Output 2:
Contains optional column (Last Name), which means it doesn’t show for all entries, only if it has a value.
id | last_name |
---|---|
1 | Jackson |
3 | Thomson |
How do I get the following?
The ID column the common and correctly associate the different outputs.
id | first_name | middle_name | last_name |
---|---|---|---|
1 | Linda | Marie | Jackson |
2 | Mary | Alice | NULL |
3 | John | Steven | Thomson |
More complicated situation
Table1
id | Entry | Result |
---|---|---|
1 | first_name | Linda |
2 | first_name | Mary |
3 | first_name | John |
1 | second_name | Liam |
2 | second_name | Violet |
3 | second_name | Charlotte |
Table2
id | Entry | Result |
---|---|---|
1 | middle_name | Marie |
2 | middle_name | Alice |
3 | middle_name | Steven |
1 | last_name | Jackson |
3 | last_name | Thomson |
Desired output is still
id | first_name | middle_name | last_name |
---|---|---|---|
1 | Linda | Marie | Jackson |
2 | Mary | Alice | NULL |
3 | John | Steven | Thomson |
3
Answers
Just LEFT JOIN to table2.
UPDATE
Based on your recent edit to the question, you can use
conditional aggregation
to achieve those updated results.View on DB Fiddle
This can be done using
LEFT JOIN
:Why would one design tables in a situation of ‘complicated situation’