簡體   English   中英

連接具有多行和相同列名的表

[英]joining table with multiple rows and same column name

表格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  

使用UNION [ALL]

select * from table1
union all
select * from table2;

PS如果單個SELECT語句存在任何重復的行,則UNION會刪除重復項,但UNION ALL連接行,即使它們是重復項也是如此。

如果您確實需要“聯接” 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”將被刪除。 並且由於凝聚函數,將返回“名稱”,“性別”列的第一個非null值。

您甚至可以使用最大最小和總和來代替合並。

ps如果桌上沒有PK,請當心!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM