如何进行正确的外连接?

时间:2014-07-20 09:43:39

标签: sql join outer-join

我正在使用OE模式并尝试在每个仓库中查看项目#和数量,如果任何仓库没有项目,那么它应该显示0项目。我正在运行SQL,它没有显示0项数量。

select i.product_id,w.warehouse_name ,(i.quantity_on_hand)
from inventories i
right outer join warehouses w
on (i.warehouse_id=w.warehouse_id)
order by 1

我希望看到这样的结果:

PRODUCT_ID WAREHOUSE_NAME                      NVL(I.QUANTITY_ON_HAND,0)
---------- ----------------------------------- -------------------------
  2262 Sydney                                                     35
  2262 Beijing                                                    50
  2262 Bombay                                                     35
  2262 San Francisco                                             155
  2262 Seattle, Washington                                        77
       Toronto                                                     0
       New Jersey                                                  0
       Southlake, Texas                                            0
       Mexico City                                                 0
  3501 Toronto                                                   220
  3501 Sydney                                                    320
  3501 Mexico City                                               294
  3501 Beijing                                                   268
  3501 San Francisco                                             353
       New Jersey                                                  0
       Southlake, Texas                                            0
       Seattle, Washington                                         0
       Bombay                                                      0

1 个答案:

答案 0 :(得分:0)

您希望每个仓库和每个产品都能看到一行。因此,从生成此列表开始,并使用left outer join引入存在的值:

select i.product_id, w.warehouse_name, coalesce(i.quantity_on_hand, 0)
from warehouses w cross join
     (select distinct product_id from inventories) p left join
     inventories i
     on w.warehouse_id = i.warehouse_id and p.product_id = i.product_id
order by i.product_id, w.warehouse_name;