在t-sql中左外连接

时间:2012-12-21 16:26:31

标签: sql sql-server tsql sql-server-2008-r2

我有以下两张表。我正在使用SQL Server 2008 R2

Create table #tmp1 (
a char(1)
)

Create table #tmp2 (
id int,
a char(1),
val int
)

insert #tmp1 values ('A')
insert #tmp1 values ('B')
insert #tmp1 values ('C')

insert #tmp2 values (1,  'A', 10)
insert #tmp2 values (1,  'B', 20)
insert #tmp2 values (2,  'A', 30)
insert #tmp2 values (2,  'C', 40)

select * from #tmp1 t1 left outer join #tmp2 t2 on t1.a = t2.a
order by t2.id

返回结果集

A   1   A   10
B   1   B   20
C   2   C   40
A   2   A   30

我想拥有以下结果集

 A     1    A       10
 B     1    B       20
 C     1    null    null
 A     2    A       30
 B     2    null    null
 C     2    C       40

现在我通过创建一个像这样的交叉连接然后进行外连接的新表来实现这个目标

select * into #tmp3 from #tmp1 cross join (select distinct ID from #tmp2) t
select * from #tmp3 t1 left outer join #tmp2 t2 on t1.a = t2.a and t1.id = t2.id

有更好的方法吗?

由于

2 个答案:

答案 0 :(得分:3)

为了得到你想要的东西,你需要一个"驾驶"表。也就是说,您需要所有组合的完整列表,然后加入其他表以获取匹配项。这是一种方式:

select t1.a, t2.*
from (select t1.a as a, t2.id as id
      from (select distinct a from #tmp1 t1) t1
           cross join
           (select distinct id from #tmp2 t2) t2
     ) driving left outer join
     #tmp1 t1
     on t1.a = driving.a left outer join
     #tmp2 t2
     on t2.id = driving.id and
        t2.a = driving.a
order by t2.id

答案 1 :(得分:0)

您正在寻找的是#tbl1中值的笛卡尔积和#tbl2中id列中的值。因为#tbl2.id中的值不是唯一的,所以为每个#tbl2.id值创建一个带有行的附加表可能是更好的设计。然后你可以使用这个解决方案:

Create table #tmp1 (
a char(1)
)

Create table #tmp2 (
id int,
a char(1),
val int
)

Create table #tmp3 (
id int
)

insert #tmp1 values ('A')
insert #tmp1 values ('B')
insert #tmp1 values ('C')

insert #tmp3 values (1)
insert #tmp3 values (2)

insert #tmp2 values (1,  'A', 10)
insert #tmp2 values (1,  'B', 20)
insert #tmp2 values (2,  'A', 30)
insert #tmp2 values (2,  'C', 40)

SELECT  t3.id,t1.a,t2.val
FROM    #tmp1 AS t1
CROSS JOIN #tmp3 AS t3
LEFT OUTER JOIN #tmp2 AS t2
ON t1.a = t2.a AND t3.id = t2.id
ORDER BY t3.id, t1.a;

如果这不是一个选项,请改用:

SELECT  t3.id,t1.a,t2.val
FROM    #tmp1 AS t1
CROSS JOIN (SELECT DISTINCT id FROM #tmp2) AS t3
LEFT OUTER JOIN #tmp2 AS t2
ON t1.a = t2.a AND t3.id = t2.id
ORDER BY t3.id, t1.a;