2015-12-22 146 views
1

我有兩個表,但第二個表的列大於第一個表(InfoDate)。SQL:當記錄不存在於第二個表中時,從第一個表插入第二個表

表1

KID  ParentID   KLevel 
---------------------------------------- 
1   0     1 
2   1     2 
3   1     2 

表2

KID ParentID KLevel  InfoDate 
------------------------------------------------------------  
2 1   2   2015-12-31 00:00:00.000 

我想從第一表到,並非在第二表與條件存在第二表中插入所有記錄InfoDate=2015-12-31 00:00:00.000

例如,與KID=1KID=3這個樣本例如記錄必須被插入到表2

我做的:

insert into table2 (KID , ParentID , KLevel) 
select KID , ParentID , KLevel from table1 
where not EXISTS(
    SELECT KID , ParentID , KLevel FROM table2 WHERE InfoDate = '2015-12-31 00:00:00.000' 
); 

(0 row(s) affected)

能不能幫我,好嗎?

+0

定義'不存在'是否存在表之間的一個鍵,告訴你一個記錄不存在? –

回答

2

您的WHERE NOT EXISTS...條件沒有意義。現在你只是檢查,如果沒有InfoDate = '2015-12-31 00:00:00.000'行。由於顯然存在這樣的行,所以沒有記錄受到影響。

試試這個:

INSERT INTO [table2] (
     [KID] 
    , [ParentID] 
    , [KLevel]) 
SELECT 
     [KID] 
    , [ParentID] 
    , [KLevel] 
FROM [table1] 
WHERE NOT EXISTS (
    SELECT 
     [KID] 
     , [ParentID] 
     , [KLevel] 
    FROM [table2] 
    WHERE [InfoDate] = '2015-12-31 00:00:00.000' 
     AND [table1].[KID] = [table2].[KID] 
     AND [table1].[ParentID] = [table2].[ParentID] 
     AND [table1].[KLevel] = [table2].[KLevel]) 
1

使用任何鍵值獲取不存在的記錄。

insert into table2 (KID , ParentID , KLevel) 
select KID , ParentID , KLevel from table1 
where KID NOT IN (
    SELECT KID FROM table2 WHERE InfoDate = '2015-12-31 00:00:00.000' 
); 
0

您需要兩個查詢相關爲:如果KID是在表中是唯一

insert into table2 (KID , ParentID , KLevel) 
select t1.KID , t1.ParentID , t1.KLevel 
from table1 t1 
where not EXISTS(
SELECT * 
FROM table2 t2 
WHERE t2.KID = t1.KID AND t2.ParentID = t1.ParentID AND t2.KLevel = t1.KLevel 
AND t2.InfoDate = '2015-12-31 00:00:00.000' 
); 
0

...

插入到表2(KID,PARENTID ,KLevel) 從表1中選擇KID,ParentID,KLevel 其中table1.KID不在( SELECT distinct distinct KID FROM table2 WHERE Info日期='2015-12-31 00:00:00.000');

相關問題