2

我在 MySQL 服务器上有两个表:T1 和 T2。ID 是 T1 的主键,ID 是 T2 的外键。

我的问题是:如果我知道与它们相关的 ID(值)但只有在 T1 中找不到该 ID 的情况下,如何在 T2 中插入一些值(使用单个查询)?

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 回答