【问题标题】:joining table with multiple rows and same column name连接具有多行和相同列名的表
【发布时间】:2018-04-16 10:32:37
【问题描述】:

表 1

id | name | gender  
1  | ABC  |  M  
2  | CDE  |  M  
3  | FGH  |  M  


表2

id | name | gender  
4  | BAC  |  F  
5  | DCE  |  F  
6  | GFH  |  F  


如何像这样在 oracle 数据库中进行输出:

id | name | gender  
1  | ABC  |  M  
2  | CDE  |  M  
3  | FGH  |  M  
4  | BAC  |  F  
5  | DCE  |  F  
6  | GFH  |  F  

【问题讨论】:

    标签: sql oracle union union-all


    【解决方案1】:

    使用UNION [ALL]:

    select * from table1
    union all
    select * from table2;
    

    附:如果个别SELECT 语句存在任何重复行,UNION 将删除重复行,但UNION ALL 连接行,即使它们是重复行。

    【讨论】:

    • 谢谢你,先生#Barbaros Ozhan
    • 澄清一下:union 连接结果并删除重复条目。 union all 连接所有结果并且不删除重复项。在您的特殊情况下,union 会产生相同的结果。
    • @Chriz 好的,谢谢,你说的是真的,但在这种情况下,两个选项都可以使用,因为没有重复的行。我把 [ ALL ] 放在括号里,再次感谢您。
    • @BarbarosÖzhan... 我建议使用col1, col2, col3,.. coln 而不是select *
    • @BarbarosÖzhan... 你怎么知道这两个表具有相同的结构(即相同的列数)。可能是 1 个表有 2 个列,而其他表只有 1 个列。
    【解决方案2】:

    如果你真的需要“加入” 2 个表:

    with a as (
      select 1 id, 'ABC' name, 'M' gender from dual union all
      select 2 id, 'CDE' name, 'M' gender from dual union all
      select 3 id, 'FGH' name, 'M' gender from dual ), 
    b as (
      select 4 id, 'BAC' name, 'F' gender from dual union all
      select 5 id, 'DCE' name, 'F' gender from dual union all
      select 6 id, 'GFH' name, 'F' gender from dual )
    select coalesce(a.id, b.id) id,
           coalesce(a.name, b.name) name,
           coalesce(a.gender, b.gender) gender
      from a
      full join b
        on a.id = b.id
        /* if name, gender not in pk */
    --   and a.name = b.name
    --   and a.gender = b.gender
    ;
    

    在这种情况下,所有重复的“ID”都将被删除。并且由于coalesce函数,将首先返回“name”的非空值,“gender”列。

    您甚至可以使用greatestleast 和 ets,而不是合并..

    附言。桌上没有PK的要小心!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-08
      • 2016-10-05
      • 2016-03-24
      • 1970-01-01
      • 1970-01-01
      • 2015-10-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多