2012-10-05 29 views
2

我在MySQL服務器上有兩個表:T1和T2。 ID是我的主鍵,而ID是T2的外鍵。如果我知道與它們(值)相關的ID,但只有在T1中沒有找到這個ID的情況下,我如何在T2中插入一些值(使用單個查詢)?SQL:如果在另一個表中找不到ID(使用單個查詢)

T1 
id,c1,c2,c3,many other columns 
example id:'fry54632' //yes, it is not numerical if matters 

T2 
id,cc1,cc2,cc3,few other columns 
example id:'fry54632', cc1,cc2,cc3... have nothing in common with c1,c2,c3 

myDataSource: 
countains id, which is same for T1 and T2 and contains some other data that should be 
inserted in T2 but not in T1 

我想我應該用這樣的事情,但我不知道:

insert into t2 (col1,col2,col3) 
select 'const1','const2','const3' 
from t1 where not exists 
(select id from t1 t --...t1, I mean: insert 'const1'...and etc strings in t2 if 
--specified ID was not found in t1} 
where t.id='someID but not t2.id') 
+0

你想插入一行或許多? –

+0

我想要插入多行而非單個行。 –

+0

你說你知道與這些值相關的ID,但是在T1中找不到這個ID。它在哪裏發現? –

回答

3
INSERT INTO T1 (ID, Col1, Col2) 
SELECT ISNULL(T1.ID,-1), ISNULL(T1.Col1,'Arbatory Value'), ISNULL(T1.Col2,'Arbatory Value') 
FROM T2 
LEFT OUTER JOIN T1 
ON T2.ID = T1.ID 
WHERE T1.ID IS NULL 
+1

這到底做了什麼? –

+1

根據ID連接2個表。在沒有連接的情況下,創建一個行並插入一個常量,在這種情況下,將-1插入到T2 –

+0

非常有趣。謝謝!但是,沒有更好的方法...也許只是使用嵌套查詢或..? –

相關問題