2015-01-15 103 views
0

我有點難倒我想做的事情,因爲我不是SQL專家。我需要從表X中提取一個ID列表,例如CustomerOrderID。然後,如果CustomerOrderID的產品詳細信息行尚未存在於表Y中,則需要將CustomerOrderID,ProductType和ProductDescription插入表Y.請記住,在此情況下,需要將表X中的CustomerOrderId插入表Y中。有任何想法嗎?需要SQL的建議

回答

1

使用NOT EXISTS過濾CustomerOrderID這是已經存在於tableY

INSERT INTO TableY 
      (CustomerOrderID, 
      ProductType, 
      ProductDescription) 
SELECT CustomerOrderID, 
     ProductType, 
     ProductDescription 
FROM TableX X 
WHERE NOT EXISTS (SELECT 1 
        FROM TableY Y 
        WHERE X.CustomerOrderID = Y.CustomerOrderID) 

或使用NOT IN操作

INSERT INTO TableY 
      (CustomerOrderID, 
      ProductType, 
      ProductDescription) 
SELECT CustomerOrderID, 
     ProductType, 
     ProductDescription 
FROM TableX 
WHERE CustomerOrderID NOT IN (SELECT Y.CustomerOrderID 
        FROM TableY Y) 
0

不知道我完全理解你的結構,但我認爲你正在尋找例如:

INSERT INTO TableY (CustomerOrderID, ProductType, ProductDescription) 
SELECT CustomerOrderID, ProductType, ProductDescription 
    FROM TableX 
    WHERE NOT EXISTS 
     (SELECT * FROM TableY 
      WHERE TableY.CustomerOrderID = TableX.CustomerOrderID 
       AND TableY.ProductType = TableX.ProductType 
       AND TableY.ProductDescription = TableX.ProductDescription 
     ) 
0

您不需要使用相關的子查詢或NOT IN命令。這可以通過左外連接來完成,並且幾乎肯定會表現得更好

insert into TableY (CustomerID, ProductType, ProductDescription) 
select CustomerID, ProductType, ProductDescription 
from TableX x 
left outer join TableY y 
    on x.CustomerID = y.CustomerID 
where y.CustomerID is null 
+0

謝謝大家!我用你的建議Xedni。它速度很快,我喜歡簡單。再次感謝你。 – amyh2005 2015-01-20 00:55:16