I have two tables:
Table1
id | col1 | col2 | other_id
---------------------------
1 | val1 | val2 | 2
2 | val3 | val4 | 3
Table2
id | col3 | other_id
--------------------
1 | val5 | 4
And I want to join this two tables in this way:
id | col1 | col2 | col3 | other_id
-----------------------------------
1 | val1 | val2 | NULL | 2
2 | val3 | val4 | NULL | 3
1 | NULL | NULL | val5 | 4
I create this SQL query:
(
SELECT * FROM table1 AS M LEFT JOIN table2 AS D ON M.other_id = D.other_id
)
UNION
(
SELECT * FROM table1 AS M RIGHT JOIN table2 AS D ON M.other_id = D.other_id
)
Result:
id | col1 | col2 | other_id | id | col3 | other_id
------------------------------------------------------
1 | val1 | val2 | 2 | NULL | NULL | NULL
2 | val3 | val4 | 3 | NULL | NULL | NULL
NULL | NULL | NULL | NULL | 1 | val5 | 4
But I get multiple columns with same labels. I don’t want to use aliases, just join columns with the same name.
You can use
UNION ALLfor this and just put placeholders for the columns that do not exist in both tables:See SQL Fiddle with Demo
Result: