SQL 左外连接不返回左侧的所有行 table(无 where 子句过滤器)

SQL Left Outer Join not returning all rows from left table (no where clause filter)

我有一个左外连接,它 return 没有来自“左”table 的所有行。我没有 where 子句,因此在加入后不应应用过滤。

我期待:

Product 1 AT 100
Product 2 AT 25
Product 4 AT 57
Product 1 GR 45
Product 2 GR 22
Product 3 GR 5
Product 4 GR 4
Product 3 null null

但是我漏掉了最后一行。非常感谢您对此的任何启发。

要复制它:

-- Oracle Database 19c Enterprise Edition Release 19.0.0.0.0 - Production

drop table t1;
drop table t2;


create table t1 
(ov_product          varchar2(18 byte)
,product             varchar2(18 byte)
)
/

create table t2 
(reporting_month     number
,product             varchar2(18 byte) 
,sender              varchar2(2 byte) 
,items               number 
)
/

insert into t1
(
select 'Product 1' ov_product, 'P1' product from dual
union
select 'Product 2' ov_product, 'P2' product from dual
union
select 'Product 3' ov_product, 'P3' product from dual
union
select 'Product 4' ov_product, 'P4' product from dual
);

insert into t2
(
select 202108, 'P1', 'AT', 100 from dual
union
select 202108, 'P2', 'AT', 25 from dual
union
-- no P3 for AT
select 202108, 'P4', 'AT', 57 from dual
union
select 202108, 'P1', 'GR', 45 from dual
union
select 202108, 'P2', 'GR', 22 from dual
union
select 202108, 'P3', 'GR', 5 from dual
union
select 202108, 'P4', 'GR', 4 from dual
)
;
commit;
select t1.ov_product
      ,t2.sender
      ,t2.items
  from t1
  left outer join t2
    on t1.product = t2.product
 order by 2, 1   
;

您的外部联接工作正常。

你的意思可能是分区外连接。

查看加入

中的额外query_partition_clause

PARTITION BY (sender) 仅此联接将 填补 sender 中的空白 ,如您所料。

select t1.ov_product
      ,t2.sender
      ,t2.items
  from t1
  left outer join t2
  PARTITION BY  (sender)
    on t1.product = t2.product   
 order by 2, 1


OV_PRODUCT         SE      ITEMS
------------------ -- ----------
Product 1          AT        100
Product 2          AT         25
Product 3          AT           
Product 4          AT         57
Product 1          GR         45
Product 2          GR         22
Product 3          GR          5
Product 4          GR          4

由于 t2 中有一行包含产品 3,因此左连接不会产生空值记录。

为了获得这样一条线路,您需要加入 table 个发件人(如果有的话)。或者,如果 table 不存在,您可以使用这样的 CTE

发件人(发件人)为(select 来自 t2 的不同发件人)

with senders(sender) as (select distinct sender from t2)

select t1.ov_product
      ,t2.sender
      ,t2.items
  from t1
  cross join senders
  left outer join t2
    on t1.product = t2.product
   and t2.sender = senders.sender
 order by 2, 1;