代码之家  ›  专栏  ›  技术社区  ›  sofs1 Romain Manni-Bucau

为什么左外连接查询给出的结果与子查询不同?

  •  1
  • sofs1 Romain Manni-Bucau  · 技术社区  · 6 年前

    我对db2linux运行以下查询

    select * from schemaname.A t1 LEFT OUTER JOIN schemaname.B t2 on t1.SSN = t2.mem_ssn
    where t2.mem_ssn = t1.ssn
    and t2.ind= 'Y'
    and t1.ind = 'Y'
    and t1.yyyy = '2018'
    and t2.yyyy = '2018'
    and t1.plan = '1340'
    

    select * from schemaname.A where ind = 'Y' and yyyy = '2018' and plan = '1340' and ssn in
    (select mem_ssn from schemaname.B where yyyy = '2018' and ind = 'Y')
    

    为什么会有这种区别?

    2 回复  |  直到 6 年前
        1
  •  3
  •   Gordon Linoff    6 年前

    你的 where left join 变成一个 inner join . 因此,一些行正在从 schemaname.A schemaname.B

    表中第二个表的条件 on 条款:

    select *
    from schemaname.A t1 LEFT OUTER JOIN
         schemaname.B t2
         on t1.SSN = t2.mem_ssn and
            t2.mem_ssn = t1.ssn and
            t2.ind = 'Y' and
            t2.yyyy = '2018'
    where t1.ind = 'Y' and
          t1.yyyy = '2018'
          t1.plan = '1340';
    

    条款。注意:我假设所有的常量值都是字符串,甚至那些看起来像数字的。如果它们真的是数字,你应该去掉单引号。

        2
  •  1
  •   Pavol Adam    6 年前

    第一个select实际上就像一个内部连接,因为t2的where条件中有非null值。 但是,区别仍然来自mem\u ssn不是t2中的主键。

    例如,如果mem\u ssn的某个特定值在t2中是三倍,则第一个选择将给出所有三行,但第二个带有子选择的选择仅给出一次该值(如果在t1中只有一次)。