如果值已经存在,请插入值

时间:2014-12-01 15:31:03

标签: sql sql-server tsql

INSERT INTO [dbo].[LikesRefined] (userA,userB)                  
SELECT l1.[user],l1.likes
FROM [dbo].[Like] l1
inner join [dbo].[Like] l2 on l2.[user] = l1.likes and l2.likes = l1.[user]
WHERE l1.[user] < l1.likes

如果userAuserB匹配,我会插入值[dbo].[Like][dbo].[LikesRefined]

如何只插入[dbo].[LikesRefined]中不存在的记录?

4 个答案:

答案 0 :(得分:3)

尝试合并。但是性能可能是一个问题,因为合并会强制您进行匹配/不匹配,因此即使不需要,也要更新存在的记录。

 SELECT l1.[user],l1.likes
 INTO #recordsToInsert
 FROM [dbo].[Like] l1
 inner join [dbo].[Like] l2 on l2.[user] = l1.likes and l2.likes = l1.[user]
 WHERE l1.[user] < l1.likes


MERGE LikesRefined AS T
USING #recordsToinsert AS S
ON (T.userA = S.user AND T.userB=s.likes)
WHEN NOT MATCHED BY TARGET
THEN INSERT(userA, userB) VALUES(S.user, S.likes)
WHEN MATCHED BY TARGET THEN
UPDATE T SET userA=user,userB=likes WHERE userA=user and userB=likes;

DROP TABLE #recordsToInsert

答案 1 :(得分:1)

我相信您可以将NOT EXISTS添加到您的where子句中,并检查LikesRefined表以确定它是否存在。

INSERT INTO [dbo].[LikesRefined] (userA,userB)                  
SELECT l1.[user],l1.likes
FROM [dbo].[Like] l1
inner join [dbo].[Like] l2 on l2.[user] = l1.likes and l2.likes = l1.[user]
WHERE l1.[user] < l1.likes
AND NOT EXISTS(SELECT 1 
               FROM dbo.LikesRefined 
               WHERE userA = l1.[user] AND UserB = l1.likes)

答案 2 :(得分:0)

请试试这个

if not exists (select 1 from [dbo].[LikesRefined] where (userA, userB) in
(select l1.[user],l1.likes
FROM [dbo].[Like] l1
inner join [dbo].[Like] l2 on l2.[user] = l1.likes and l2.likes = l1.[user]
WHERE l1.[user] < l1.likes))
begin

--- insert query

end;

答案 3 :(得分:0)

使用左连接

INSERT INTO [dbo].[LikesRefined] (userA,userB)

(SELECT l1.[user],l1.likes
FROM [dbo].[Like] l1
LEFT JOIN LikesRefined
ON l2.[user] = l1.likes AND l2.likes = l1.[user]
WHERE l2.user IS NULL)

select语句将返回Like表中LikesRefined中相应记录为空(即不存在)的内容。只需确保在LikesRefined中选择一个通常不可为空的字段。