如何获得以下加入
输入:
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 - -
答案 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
;
答案 5 :(得分:0)
您需要进行外部联接
SELECT *
FROM table1 t1,
table2 t2
WHERE t1.col1 = t2.col1(+)