我正在使用VS2005和SQL Server 2005。
我正在尝试执行连接3个sql表的多个INSERT INTO
SQL语句。
3个表格是:
Table1
:UserID, Username
Table2
:UserID, Status
Table3
:UserID, Username, Issue
以下是我需要执行的检查:
Table1
中存在的用户应存在于Table2
Table1
中存在的用户STATUS=DELETE
Table2
STATUS=DELETE
Table2
中没有Table1
的用户
醇>
目前我只有一个SELECT
语句,可以满足上述3个查询,而无需在第3个表中添加:
SELECT *
FROM table1 t1
FULL OUTER JOIN table2 t2 ON t1.userid = t2.userid
WHERE (t2.userid IS NULL AND t1.userid IS NOT NULL)
OR (t2.status = 'DELETE' AND t1.userid IS NOT NULL)
OR (t2.userid IS NOT NULL AND t2.status <> 'DELETE' AND t1.userid IS NULL)
对于上面的每项检查,我想INSERT
将结果导入Table3
并使用唯一的ISSUE
变量(例如,对于第1号检查,ISSUE=User exist in t1 but not t2
)< / p>
目前我正在尝试形成一个将3个表连接在一起的查询,对于第一个检查t2.userid IS NULL AND t1.userid IS NOT NULL
找到的每个结果,它会在Table3
中插入一个新行。但是我在使用SQL查询时遇到了一些问题。
INSERT INTO Table3 (userid, username, issue)
VALUES (t1.userid, t1.username, 'user not found in t2')
FULL OUTER JOIN table2 t2 ON t1.userid = t2.userid
WHERE (t2.userid IS NULL AND t1.userid IS NOT NULL)
非常感谢您的帮助。
答案 0 :(得分:2)
我没有这些表进行测试,因此语法将会很接近:
COALESCE
的{{1}}将确保您在列中插入值,因为您不确定该值是否存在于Table1或Table2中
我还使用了UserId
语句的where子句来填充CASE
列。您可以更新文本以适合您的应用程序。
Issue
答案 1 :(得分:2)
1.
Insert in to Table3(userid,issue)
SELECT t1.userid,'check no.1'
FROM table1 t1
FULL OUTER JOIN table2 t2 ON t1.userid = t2.userid
where t1.userid not null and t2.userid is null
2.
Insert in to Table3(userid,issue)
SELECT t1.userid,'check no.2'
FROM table1 t1
inner JOIN table2 t2 ON t1.userid = t2.userid
where t2.status = 'DELETE'
3.
Insert in to Table3(userid,issue)
SELECT t2.userid,'check no.3'
FROM table1 t1
right outer JOIN table2 t2 ON t1.userid = t2.userid
where t2.status = 'DELETE' and t1.userid is null