2017-09-21 58 views
2

我想找到一個簡單的(ish)方法來從3個表中選擇結果,並從每個select中選擇返回的列,並將它們全部插入到第4個表中,這將作爲基於typeId,manufacturerId和locationId的可用性「查找矩陣」。Oracle嵌套SELECT循環插入到新表

因此,例如,如果有10個TYPEID和5 MANUFACTURERID說3 LOCATIONID,我會得到10x5x3所以150行插入到表4

有表1,2 & 3之間沒有直接的聯繫,他們只是產品類型,製造商和地點的獨立表格。 後來會出現在表4 a「標誌」列,以確定其可用性真/假

這樣的事情,但我不知道語法:

SELECT DISTINCT TYPEID FROM TABLE1 
Loop 
    SELECT DISTINCT MANUFACTURERID FROM TABLE2 
    Loop 
     SELECT DISTINCT LOCATIONID FROM TABLE3 
     Loop 
      INSERT INTO TABLE4 (TYPEID,MANUFACTURERID,LOCATIONID) VALUES TYPEID,MANUFACTURERID,LOCATIONID 
     EndLoop 
    EndLoop 
EndLoop 

我相信我;已經看到這之前做過(在我認爲的程序中),但我找不到示例,任何幫助將非常感激。

回答

0

沒有循環需要:

INSERT INTO TABLE4 (TYPEID,MANUFACTURERID,LOCATIONID) 
SELECT DISTINCT TABLE1.TYPEID, TABLE2.MANUFACTURERID, TABLE3.LOCATIONID 
FROM TABLE1 
CROSS JOIN TABLE2 
CROSS JOIN TABLE3; 
2

你只需要cross join:對跨

insert into table4 (TYPEID,MANUFACTURERID,LOCATIONID) 
select 
    t1.TYPEID, 
    t2.MANUFACTURERID, 
    t3.LOCATIONID 
from (
    SELECT DISTINCT TYPEID FROM TABLE1 
) t1 cross join (
    SELECT DISTINCT MANUFACTURERID FROM TABLE2 
) t2 cross join (
    SELECT DISTINCT LOCATIONID FROM TABLE3 
) t3; 

insert into table4 (TYPEID,MANUFACTURERID,LOCATIONID) 
select distinct 
    t1.TYPEID, 
    t2.MANUFACTURERID, 
    t3.LOCATIONID 
from table1 t1 
cross join table2 t2 
cross join table3 t3 
+0

作爲參考,甲骨文文檔加入:http://docs.oracle .com/javadb/10.6.2.1/ref/rrefsqljcrossjoin.html – moneyt

+0

我會去第一個查詢。爲什麼交叉連接所有記錄(如在第二個查詢中),當我們只想加入不同的ID時? –

+1

@ThorstenKettner - 我同意。第二個是顯而易見的,但第一個是正確的路要走。 – GurV