EDIT: An extension to this question can be found here
I want to join four different tables with SQLite which have just two columns in common. Please take a look at following example
+--------+---+-----+-----+
| table1 | | | |
+--------+---+-----+-----+
| a | b | lon | lat |
+--------+---+-----+-----+
| 1 | 2 | 111 | 222 |
+--------+---+-----+-----+
+--------+---+-----+-----+
| table2 | | | |
+--------+---+-----+-----+
| c | d | lon | lat |
+--------+---+-----+-----+
| 3 | 4 | 333 | 444 |
+--------+---+-----+-----+
+--------+---+-----+-----+
| table3 | | | |
+--------+---+-----+-----+
| e | f | lon | lat |
+--------+---+-----+-----+
| 5 | 6 | 555 | 666 |
+--------+---+-----+-----+
+--------+---+-----+-----+
| table4 | | | |
+--------+---+-----+-----+
| g | h | lon | lat |
+--------+---+-----+-----+
| 7 | 8 | 777 | 888 |
+--------+---+-----+-----+
The tables are not connected by any foreign key. Also, the lon/lat values are different for every row. An optimal output would be:
+------+------+------+------+------+------+------+------+-----+-----+
| a | b | c | d | e | f | g | h | lon | lat |
+------+------+------+------+------+------+------+------+-----+-----+
| None | None | 3 | 4 | None | None | None | NOne | 333 | 444 |
| 1 | 2 | None | None | None | None | None | None | 111 | 222 |
| None | None | None | None | 5 | 6 | None | None | 555 | 666 |
| None | None | None | None | None | None | 7 | 8 | 777 | 888 |
+------+------+------+------+------+------+------+------+-----+-----+
- Again, this is my end goal - lat/lon values are not interconnected between the tables:
- a | b | c | .. | lat | lon | instead of
- a | b | c | .. | table1.lat | table2.lat | ...
- Appreciate your help!
- My current code
-- First two tables
CREATE VIEW ab AS
SELECT * FROM table1 LEFT JOIN table2 ON ???
UNION ALL
SELECT * FROM table2 LEFT JOIN table1 ON ?? WHERE ?? IS NULL
-- 3rd and 4th table
CREATE VIEW cd AS
SELECT * FROM table3 LEFT JOIN table4 ON ??
UNION ALL
SELECT * FROM table4 LEFT JOIN table3 ON ?? WHERE ?? IS NULL
-- -- JOIN
SELECT * FROM cd LEFT JOIN ab ON ??
UNION ALL
SELECT * FROM cd LEFT JOIN ab ON ?? WHERE ?? IS NULL
Assuming that your sample tables has data like below
Table1:
Table2:
Table3
Table4
and you want to merge the records, you can use
union all
.Result:
DEMO