我有两个表,我想在没有完全外部联接的情况下合并,因为它在h2 db中不工作。我必须创建select sql查询:我也尝试过使用UNION,但我认为使用UNION是不可能的。
表1
id c_id s_id p_date
---------------------------------------------
1 1 1 2020-10-10
2 1 1 2020-10-11
3 2 1 2020-10-11
4 2 2 2020-10-12表2
id c_id s_id s_date
---------------------------------------------
1 1 1 2020-10-15
2 1 2 2020-10-16
3 2 2 2020-10-17
4 2 2 2020-10-17我期待以下结果:
c_id s_id p_date s_date
-------------------------------------------------
1 1 2020-10-10 2020-10-15
1 1 2020-10-11 -
1 2 - 2020-10-16
2 1 2020-10-11 -
2 2 2020-10-12 2020-10-17
2 2 - 2020-10-17请帮助取得这一结果。
发布于 2020-08-10 22:00:35
您可以这样使用union all:
select t1.c_id, t1.s_id, t1.p_date, t2.s_date
from table1 t1 left join
table2 t2
on t1.c_id = t2.c_id and t1.s_id = t2.s_id
union all
select t2.c_id, t2.s_id, t1.p_date, t2.s_date
from table2 t2 left join
table1 t1
on t1.c_id = t2.c_id and t1.s_id = t2.s_id
where t1.c_id is null;第一个子查询获取两个表之间匹配的所有行,再加上table2与table1没有匹配的行。
第二个子查询从table2获得在table1中没有匹配的额外行。
这里是db<>fiddle。
https://stackoverflow.com/questions/63348574
复制相似问题