如何获取以下连接查询

时间:2013-07-26 14:03:03

标签: sql oracle join

如何获得以下加入

输入:

table1:     table2:
col1        Col1   col2 col3
A           A        1    2 
B           B        4    5
C   

输出:

col1   col2 col3 
A       1     2
B       4     5
c       -     -

6 个答案:

答案 0 :(得分:0)

您可以使用full outer join

执行此操作
select coalesce(t1.col1, t2.col1), t2.col2, t2.col3
from table1 t1 full outer join
     table2 t2
     on t1.col1 = t2.col1;

这将返回两个表中的所有行,即使是那些不匹配的行(它同时是左外连接和右外连接)。

您也可以使用union all和聚合:

执行此操作
select col1, max(col2) as col2, max(col3) as col3
from ((select col1, NULL as col2, NULL as col3
       from table1
      ) union all
      (select col1, col2, col3
       from table2
      )
     ) t
group by col1;

答案 1 :(得分:0)

SELECT t1.col1, t2.col2, t2.col3
  FROM table1 t1
  LEFT JOIN table2 t2 ON t1.col1=t2.col1
;

答案 2 :(得分:0)

select t1.col1, t2.col2, t2.col3
from table1 t1
left outer join table2 t2
on t1.col1 = t2.col1

答案 3 :(得分:0)

如果你不是' - '

,也许这样的话
SELECT t1.col1, coalesce(t2.col2,'-') as col2, coalesce(t2.col3,'-') as col3
FROM table1 t1
LEFT JOIN table2 t2 ON t1.col1=t2.col1

答案 4 :(得分:0)

查看我的sqlfiddle

create table table1(
    col1 char(1)
  );

insert into table1 values('A');
insert into table1 values('B');
insert into table1 values('C');


create table table2(
    col1 char(1),
    col2 int,
    col3 int
  );

insert into table2 values('A',1,2);
insert into table2 values('B',4,5);


select 
  t1.col1, 
  coalesce(t2.col2,'-'), 
  coalesce(t2.col3,'-')
from 
  table1 t1
left join table2 t2 on t1.col1=t2.col1
;

http://sqlfiddle.com/#!2/bc768/2

答案 5 :(得分:0)

您需要进行外部联接

SELECT * 
  FROM table1 t1,
       table2 t2
WHERE t1.col1 = t2.col1(+)