我有两张桌子:
Table1
id | col1 | col2 | other_id
---------------------------
1 | val1 | val2 | 2
2 | val3 | val4 | 3
Table2
id | col3 | other_id
--------------------
1 | val5 | 4
我希望以这种方式加入这两个表:
id | col1 | col2 | col3 | other_id
-----------------------------------
1 | val1 | val2 | NULL | 2
2 | val3 | val4 | NULL | 3
1 | NULL | NULL | val5 | 4
我创建了这个SQL查询:
(
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
)
结果:
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
但我得到多个具有相同标签的列。我不想使用别名,只需加入具有相同名称的列。
答案 0 :(得分:2)
您可以使用UNION ALL
,只为两个表中不存在的列添加占位符:
select t1.id, t1.col1, t1.col2, null col3, t1.other_id
from table1 t1
union all
select t2.id, null col1, null col2, t2.col3, t2.other_id
from table2 t2
结果:
| ID | COL1 | COL2 | COL3 | OTHER_ID |
--------------------------------------------
| 1 | val1 | val2 | (null) | 2 |
| 2 | val3 | val4 | (null) | 3 |
| 1 | (null) | (null) | val5 | 4 |
答案 1 :(得分:2)
如果您想在不使用别名的情况下实现此目的,则必须手动使用每一列。
(SELECT M.ID,M.Col1,M.Col2,D.Col3,M.Other_ID
FROM table1 AS M
LEFT JOIN table2 AS D
ON M.other_id = D.other_id)
UNION
(SELECT D.ID,M.Col1,M.Col2,D.Col3,D.Other_ID
FROM table1 AS M
RIGHT JOIN table2 AS D
ON M.other_id = D.other_id);
结果
| ID | COL1 | COL2 | COL3 | OTHER_ID |
--------------------------------------------
| 1 | val1 | val2 | (null) | 2 |
| 2 | val3 | val4 | (null) | 3 |
| 1 | (null) | (null) | val5 | 4 |
答案 2 :(得分:1)
SELECT id, col1, col2, '' col3, other_id
FROM table1
UNION
SELECT id, '' col1 , '' col2, col3, other_id
FROM table2
答案 3 :(得分:-1)
Union希望表格具有相同的字段。你可以把'人工'字段用来做那个