加入并删除笛卡尔积

时间:2015-01-08 23:02:10

标签: sql database oracle oracle-sqldeveloper database-administration

我有5个区域,每个区域包含1个商店和1个仓库。我有一个包含区域和相应商店和仓库的表。我还有一张表格列出了商店和仓库的库存。最后,有一个表格列出仓库的允许数量。如果我现在查看库存表,它会说:

FACILITY ID        ITEM_NUMBER    QTY
  STORE 1              15D         2 
 WAREHOUSE 1           15D         1

问题是,商店1和仓库1属于区域1,我希望以这种格式看到它:

REGION    WAREHOUSE    QTY OH     STORE    QTY OH 
  1           1          2          1         1

等等......所以我编写了以下SQL:

Create or replace view REGION_BALANCES
as
with WAREHOUSES as 
(select A.REGION_CODE, A.REG_DESC, A.WAREHOUSE_NUMBER, A.FACILITY_ID,
        C.ITEM_NUMBER, sum(C.IN_STOCK_QTY) as IN_STOCK_QTY,
        B.ALLOWED_QTY
 from   REG_WHS_STR_ASSOC A                                    join
        ALLOWANCES        B on (A.FACILITY_ID = B.FACILITY_ID) join
        INVENTORIES       C on (A.FACILITY_ID = FACILITY_ID) and (B.ITEM_NUMBER = C.ITEM_NUMBER)
 group  by A.REGION_CODE, A.REG_DESC, A.WAREHOUSE_NUMBER, C.ITEM_NUMBER, B.ALLOWED_QTY), 
STORES as 
(select A.REGION_CODE, A.REG_DESC, A.STORE_NUMBER, A.FACILITY_ID, B.ITEM_NUMBER,
        sum(B.IN_STOCK_QTY) as IN_STOCK_QTY
 from   REG_WHS_STR_ASSOC A                                    join
        INVENTORIES       B on (A.FACILITY_ID = B.FACILITY_ID)
 group  by A.REGION_CODE, A.REG_DESC, A.STORE_NUMBER, B.ITEM_NUMBER
)
select A.REGION_CODE, A.REG_DESC, A.WAREHOUSE_NUMBER, A.FACILITY_ID,
       WAREHOUSES.ITEM_NUMBER, WAREHOUSES.IN_STOCK_QTY, WAREHOUSES.ALLOWED_QTY,
       STORES.STORE_NUMBER, STORES.FACILITY_ID, STORES.ITEM_NUMBER, STORES.IN_STOCK_QTY
from   REG_WHS_STR_ASSOC A                                             join
       WAREHOUSES          on (A.REGION_CODE = WAREHOUSES.REGION_CODE) join
       STORES              on (A.REGION_CODE = STORES.REGION_CODE)
order by 5,1 asc;

我已经改变了我的连接,从左连接到右连接,交叉连接到内连接;但是,我要么得到30条记录(我需要数百条记录),要么我得到笛卡尔积。任何人都可以为我做错的事提供建议吗?

1 个答案:

答案 0 :(得分:0)

这是怎么回事?您是否正在使用某些编程来提取此数据。

SELECT
REGION_CODE, REG_DESC, WAREHOUSE_NUMBER, WAREHOUSE_FACILITY_ID, STORE_NUMBER, STORE_FACILITY_ID,
FACILITY_ID, ITEM_NUMBER, IN_STOCK_QTY

FROM REG_WHS_STR_ASSOC R 
INNER JOIN Inventories I ON I.FACILITY_ID = R.WAREHOUSE_FACILITY_ID OR I.FACILITY_ID = R.STORE_FACILITY_ID
GROUP BY REGION_CODE, REG_DESC, WAREHOUSE_NUMBER, WAREHOUSE_FACILITY_ID, STORE_NUMBER, STORE_FACILITY_ID,
FACILITY_ID, ITEM_NUMBER, IN_STOCK_QTY

我认为这就是你要找的东西。为了压扁它,我认为你必须使用子查询 - 这很好但可能效率不高。但我认为这会让你得到你想要的东西 - 为了你的目的,你将不得不为它添加更多东西