即使存在不匹配,也要加入SQL

时间:2017-07-20 16:01:17

标签: sql join

我有3个表格如下:

表A

[ID_A] [name]
1      hello
2      world

表B

[ID_B] [name]
1      foo
2      bar
3      booboo

表C

[ID_C] [ID_A] [ID_B]
1      1      1
2      1      2
3      2      2

我想要的是:对于每个A.name,根据其自身与B中所有条目之间的链接的存在,返回0或1的行

结果:

[A.ID] [B.ID] [res]
1      1      1
1      2      1
1      3      0
2      1      0
2      2      1
2      3      0

我尝试使用普通连接,完全外连接(在我看来它们完美地工作),但我无法设法做到这一点,因为如果没有要加入的行,我就无法执行连接上

3 个答案:

答案 0 :(得分:0)

declare @tablea table ( ID_A int, name varchar(12) )
declare @tableb table ( ID_B int, name varchar(12) )
declare @tablec table ( ID_C int, ID_A int, ID_B int )

insert @tablea values (1, 'hello'), (2, 'world')
insert @tableb values (1, 'foo'), (2, 'bar'), (3, 'booboo')
insert @tablec values (1, 1, 1), (2, 1, 2), (3, 2, 2)

select 
    ID_A as [A.ID],
    ID_B as [B.ID],
    (select count(*) from @tablec c where a.ID_A = c.ID_A and b.ID_B = c.ID_B) [res]
from @tablea A, @tableb B
order by a.ID_A, b.ID_B

答案 1 :(得分:0)

您需要CROSS JOINLEFT JOIN

SELECT A.id_a, 
       B.id_b, 
       Coalesce(res, 0)  as res
FROM   tablea A 
       CROSS JOIN tableb B 
       LEFT JOIN (SELECT DISTINCT id_a,id_b,1 AS res 
                  FROM   tablec) C 
              ON A.id_a = C.id_a
                 AND B.id_b = C.id_b 

答案 2 :(得分:0)

执行左连接,但从您想要所有可能条目的表开始。不要真正加入每用户帐户,因此它会强制每个人的笛卡尔结果到名称查找表。最后左连接以识别它是否存在。

select
      a.name as NameFromA,
      a.id_a,
      b.name as NameFromB,
      b.id_b,
      case when c.id_c IS NULL then 0 else 1 end as ExistsInTableC
   from
      TableA a
         JOIN TableB b   (no actual JOIN ON clause)
            LEFT JOIN TableC c
               on a.id_a = c.id_a
              AND b.id_b = c.id_b