首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用不同的列连接两个表

用不同的列连接两个表
EN

Stack Overflow用户
提问于 2020-08-10 21:58:31
回答 1查看 30关注 0票数 0

我有两个表,我想在没有完全外部联接的情况下合并,因为它在h2 db中不工作。我必须创建select sql查询:我也尝试过使用UNION,但我认为使用UNION是不可能的。

表1

代码语言:javascript
复制
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

代码语言:javascript
复制
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

我期待以下结果:

代码语言:javascript
复制
    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

请帮助取得这一结果。

EN

回答 1

Stack Overflow用户

发布于 2020-08-10 22:00:35

您可以这样使用union all

代码语言:javascript
复制
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;

第一个子查询获取两个表之间匹配的所有行,再加上table2table1没有匹配的行。

第二个子查询从table2获得在table1中没有匹配的额外行。

这里是db<>fiddle。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63348574

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档