我在MSSQL中有两个表,结构相同T1和amp; T2。两个表都可以在Id上加入Id,但T2可能不包含与Id中的Id相关联的AccountId。
T1 Id AccountId Name T2 Id AccountId Name
111 5555 John 111 5555 John
122 5555 David 133 5555 Sharon
133 5555 Sharon
以下是我尝试过的代码但结果不起作用?
INSERT INTO T3
SELECT T1.Id,T1.AccountId,T1.Name
FROM T1
INNER JOIN T2 T2.Id = T1.id
LEFT OUTER JOIN T1.AccountId = T2.AccountId
WHERE AccountId = 5555
预期的结果是将不在T1中的值插入T3
答案 0 :(得分:2)
您需要where
子句:
INSERT INTO T3(Id, AccountId, Name)
SELECT T1.Id, T1.AccountId, T1.Name
FROM T1 LEFT JOIN
T2
ON T2.Id = T1.id
WHERE T2.AccountId IS NOT NULL;
注意:
LEFT JOIN
。我不知道INNER JOIN
的用途。JOIN
后面都应跟ON
子句。INSERT
时列出列。WHERE
才能找到不匹配的内容。NOT EXISTS
。答案 1 :(得分:0)
这应该是你想要的:
CREATE TABLE #T1 (id int, AccountId int, [Name] varchar(6));
CREATE TABLE #T2 (id int, AccountId int, [Name] varchar(6));
CREATE TABLE #T3 (id int, AccountId int, [Name] varchar(6));
INSERT INTO #T1
VALUES (111,5555,'John '),
(122,5555,'David '),
(133,5555,'Sharon');
INSERT INTO #T2
VALUES (111,5555,'John '),
(133,5555,'Sharon');
INSERT INTO #T3 (id, AccountId, [Name])
SELECT T1.id,
T1.AccountId,
T1.[Name]
FROM #T1 T1
LEFT JOIN #T2 T2 ON T1.ID = T2.id
WHERE T2.id IS NULL;
SELECT *
FROM #t3;
DROP TABLE #T1;
DROP TABLE #T2;
DROP TABLE #T3;