/*
数据表的连接有: 
1、内连接(自然连接): 只有两个表相匹配的行才能在结果集中出现 
2、外连接: 包括 
(1)左外连接(左边的表不加限制) 
(2)右外连接(右边的表不加限制) 
(3)全外连接(左右两表都不加限制) 
3、自连接(连接发生在一张基表内) 
*/
--左连接1 无论b表中有没有得到匹配的时间,左边的a表的数据都会显示出来
select a.*, nvl(b.prd_quantity, 0) as prd_quantity
  from som_ptm_detail a
  left join (select som_ptm_detail_id,
                    sum(nvl(prd_quantity, 0)) prd_quantity
               from prd_order
              group by som_ptm_detail_id) b
    on a.keyid = b.som_ptm_detail_id
 where (nvl(a.ord_number, 0) + nvl(a.bakup_storage, 0) - nvl(a.storage, 0) +
       nvl(a.gift_quantity, 0)) > nvl(b.prd_quantity, 0)
 order by a.serial_no;
 
 --左连接2 无论b表中有没有得到匹配的时间,左边的a表的数据都会显示出来
 --"(+)"所在位置的另一侧为连接的方向
 --左连接说明等号左侧的所有记录均会被显示,无论其在右侧是否得到匹配。
  select a.*, nvl(b.prd_quantity, 0) as prd_quantity
  from som_ptm_detail a
  , (select som_ptm_detail_id,
                    sum(nvl(prd_quantity, 0)) prd_quantity
               from prd_order
              group by som_ptm_detail_id) b
    where a.keyid = b.som_ptm_detail_id(+)
 and (nvl(a.ord_number, 0) + nvl(a.bakup_storage, 0) - nvl(a.storage, 0) +
       nvl(a.gift_quantity, 0)) > nvl(b.prd_quantity, 0)
  order by a.serial_no;
  
  --右连接 无论a表有没有匹配的数据,b表的数据都显示出来
  --"(+)"所在位置的另一侧为连接的方向
  --右连接说明等号右侧的所有记录均会被显示,无论其在左侧是否得到匹配。
  select a.*, nvl(b.prd_quantity, 0) as prd_quantity
  from som_ptm_detail a
  , (select som_ptm_detail_id,
                    sum(nvl(prd_quantity, 0)) prd_quantity
               from prd_order
              group by som_ptm_detail_id) b
    where a.keyid(+) = b.som_ptm_detail_id
 and (nvl(a.ord_number, 0) + nvl(a.bakup_storage, 0) - nvl(a.storage, 0) +
       nvl(a.gift_quantity, 0)) > nvl(b.prd_quantity, 0)
  order by a.serial_no;
  
  --右连接2 
   select a.*, nvl(b.prd_quantity, 0) as prd_quantity
  from som_ptm_detail a
  right join (select som_ptm_detail_id,
                    sum(nvl(prd_quantity, 0)) prd_quantity
               from prd_order
              group by som_ptm_detail_id) b
    on a.keyid = b.som_ptm_detail_id
 where (nvl(a.ord_number, 0) + nvl(a.bakup_storage, 0) - nvl(a.storage, 0) +
       nvl(a.gift_quantity, 0)) > nvl(b.prd_quantity, 0)
  order by a.serial_no;
 
 --内连接(自然连接): 只有两个表相匹配的行才能在结果集中出现
 select a.*, nvl(b.prd_quantity, 0) as prd_quantity
  from som_ptm_detail a
  , (select som_ptm_detail_id,
                    sum(nvl(prd_quantity, 0)) prd_quantity
               from prd_order
              group by som_ptm_detail_id) b
    where a.keyid = b.som_ptm_detail_id
 and (nvl(a.ord_number, 0) + nvl(a.bakup_storage, 0) - nvl(a.storage, 0) +
       nvl(a.gift_quantity, 0)) > nvl(b.prd_quantity, 0)
 order by a.serial_no;