我正在尝试在当前的SQL INSERT INTO语句中添加查询。下面是我的表和当前的sql语句。
我有3张桌子:
表1 : UserID ,用户名。
表2 :用户ID ,状态。
表3 :用户ID ,用户名,问题
目前我只有一个SELECT语句来完成上述3项检查,并将结果插入表3中:
INSERT INTO Table3(UserId, Username, Issue)
SELECT COALESCE(t1.UserId, t2.UserId), t1.UserName
, CASE
WHEN (t2.userid IS NULL AND t1.userid IS NOT NULL)
THEN 'User exists in t1 but not in t2'
WHEN (t2.status = 'DELETE' AND t1.userid IS NOT NULL)
THEN 'User Exists in t1, but status in t2 is not DELETE'
WHEN (t2.userid IS NOT NULL AND t2.status != 'DELETE' AND t1.userid IS NULL)
THEN 'Non-Deleted user in t2 does not exist in t1'
END
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)
现在我想添加另一个额外的检查,即检查重复的用户ID,并为表3中的任何重复项插入 UserID,用户名和问题'找到重复的用户ID'。
我应该如何将此SQL查询添加到我当前的SQL语句中?
答案 0 :(得分:1)
如果您希望使用Duplicated userid found
插入记录(这会在Table3
中导致重复的UserId值,您可以使用以下代码:
INSERT INTO Table3(UserId, Username, Issue)
SELECT COALESCE(t1.UserId, t2.UserId), t1.UserName
, CASE
WHEN (t3user.UserId IS NOT NULL OR t3Status.UserId IS NOT NULL)
THEN 'Duplicated userid found'
WHEN (t2.userid IS NULL AND t1.userid IS NOT NULL)
THEN 'User exists in t1 but not in t2'
WHEN (t2.status = 'DELETE' AND t1.userid IS NOT NULL)
THEN 'User Exists in t1, but status in t2 is DELETE'
WHEN (t2.userid IS NOT NULL AND t2.status != 'DELETE' AND t1.userid IS NULL)
THEN 'Non-Deleted user in t2 does not exist in t1'
END AS Issue
FROM table1 t1
FULL OUTER JOIN table2 t2 ON t1.userid = t2.userid
LEFT JOIN Table3 AS t3user ON t1.UserID = t3user.UserId
LEFT JOIN Table3 AS t3status ON t2.UserId = t3status.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)
)