2

MySQL サーバーに T1 と T2 の 2 つのテーブルがあります。ID は T1 の主キーであり、ID は T2 の外部キーです。

私の質問は次のとおりです。それらに関連するID(値)がわかっている場合にのみ、T2に(単一のクエリを使用して)いくつかの値を挿入できますが、このIDがT1に見つからなかった場合に限りますか?

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')
4

1 に答える 1

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
于 2012-10-05T17:16:48.627 に答える