使用MINUS子查询的结果插入表中

时间:2017-10-28 18:29:55

标签: sql oracle insert subquery

我正在尝试在ORACLE上插入两个表(示例数据)中的MINUS值。我可以插入所有行,但我无法使用其他表中缺少的行:

示例数据:

SALES TABLE           SALES2 TABLE           S_DETAILS TABLE               
===================   ===================    ==================
ID_SALE|DATE_SALE     ID_SALE|DATE_SALE      ID_SALE|SALE_DETAILS
100    |12/12/2010    100    |12/12/2010     100    |SHIPPED
101    |5/10/2011     101    |5/10/2011      101    |WAITING
102    |10/9/2012                            102    |SHIPPED
103    |5/10/2011                            103    |PROCESSING

我的代码:

INSERT INTO SALES_RESUME(ID_SALE,DATE_SALE,TOTAL_SALE,SALE_DETAILS)
SELECT A.ID_SALE,A.DATE_SALE,B.TOTAL_SALE,B.SALE_DETAILS
FROM SALES A
     JOIN S_DETAILS B ON A.ID_SALE = B.ID_SALE
WHERE A.ID_SALE IN (SELECT ID_SALE FROM SALES
                    MINUS
                    SELECT ID_SALE FROM SALES2);

当ID_SALE位于生成的MINUS子查询中时,我想在SALES_RESUME中插入行,插入:

SALES_RESUME          
==============================
ID_SALE|DATE_SALE|SALE_DETAILS
102    |10/9/2012|SHIPPED
103    |5/10/2011|PROCESSING

提前致谢

2 个答案:

答案 0 :(得分:0)

您的查询似乎可以执行您想要的操作。但为什么不写这个?

WHERE A.ID_SALE NOT IN (SELECT ID_SALE FROM SALES2 WHERE ID_SALE IS NOT NULL);  -- assuming SALES2.ID_SALE is never NULL

您已经知道ID_SALE位于第一个表格中。

答案 1 :(得分:0)

如果我得到它,我认为这个查询将起作用

SELECT A.ID_SALE,A.DATE_SALE,B.TOTAL_SALE,B.SALE_DETAILS
  FROM ((select id_sale,DATE_SALE from SALES) minus (select id_sale,DATE_SALE from SALES2)) A 
       JOIN S_DETAILS B on A.id = B.id