2013-07-19 41 views
-1

我試圖插入表的語法如下:插入到表中選擇其中不存在影響0行

INSERT INTO table1(
col1, col2, col3) 
SELECT distinct 
col1, col2, getDate() 
FROM table2 WHERE NOT EXISTS(
    SELECT 1 FROM table1, table2 
    WHERE ((table1.col1 = table2.col1) or (table1.col1 is null and table2.col1 is null)) 
    AND ((table1.col2 = table2.col2) or (table1.col2 is null and table2.col2 is null))) 

但是當我運行查詢,則顯示(0行(S)的影響)。

NOT EXISTS語句中的SELECT語句返回我不想插入的正確行數。如果我嘗試在沒有WHERE NOT EXISTS語句的情況下插入表,它會插入所有內容。我只想插入不在table1中的行。

+1

請[編輯]你的問題,提供從'table1'和'table2'一些示例數據,並從'table2'您希望要插入的行。 (你的'NOT EXISTS'查詢是可怕的,但是很難建議一種特定的方法來改進它,而沒有使用一些樣本數據來做到這一點。) –

+0

瞭解'Exists'只是嘗試'從TableX中選擇*而不存在(選擇1)' – bummi

回答

0

您可以優化這個查詢了不少,但作爲一個速戰速決,你可以改變:

SELECT 1 FROM table1, table2 

到:

SELECT 1 FROM table1 

這會配合外表2到你的子查詢。

+0

這很有道理!謝謝! – DobleA

1

試試這個:

INSERT INTO table1(col1, col2, col3) 
SELECT distinct col1, col2, getDate() 
FROM table2 WHERE NOT EXISTS(
    SELECT 1 FROM table1 
    WHERE ((table1.col1 = table2.col1) or (table1.col1 is null and table2.col1 is null)) 
    AND ((table1.col2 = table2.col2) or (table1.col2 is null and table2.col2 is null))) 
+0

聖潔的廢話。我認爲那樣做了!你能解釋一下爲什麼這是有效的,而不是我所擁有的? – DobleA

+0

嗨,如果您在子查詢中使用Table2它不是主查詢,但副本。相反,如果使用主查詢的表2,則鏈接兩個表,以便結果正確。 –

+0

明白了。謝謝! – DobleA