从表中删除不匹配的数据

时间:2016-08-12 12:56:43

标签: sql sql-server join

我有一张桌子和同桌的备份。在备份后,在主表中插入了一些数据。现在我想从主表中删除数据。怎么实现呢? 让我们说桌子是#Book;'列为AuthorID,BookName,BookID。备份了BookMap'表和插入的新数据。现在想要删除这些数据。

注意:我这里没有主键。

4 个答案:

答案 0 :(得分:1)

如果您希望backup_BookMap看起来像truncate table bookmap; insert into bookmap( . . .) select . . . from backup_bookmap; ,那么您可能会考虑:

{{1}}

答案 1 :(得分:1)

如果我理解正确,您要删除已插入备份表的非备份表中的数据:

DELETE nonbackup
FROM BookMap as nonbackup
WHERE nonbackup.BookID IN
(
    SELECT BookID
    FROM BookMapBackup as backup
)

答案 2 :(得分:1)

尝试这样,

DELETE B FROM bookmark B INNER JOIN 
(
SELECT *FROM (
select *From bookmark
except
select *From bookmarkbackup)T
)T1 ON T1.AuthorID=B.AuthorID
AND T1.BookName=B.BookName
AND T1.BookID=B.BookID

答案 3 :(得分:0)

以下是您可以测试的内容:

DECLARE @book table
(
    AuthorID varchar,
    BookName varchar(255),
    BookID int
);

DECLARE @backupBook table
(
    AuthorID varchar,
    BookName varchar(255),
    BookID int
);

insert into @book values(1, 'book1', 1 )
insert into @book values(2, 'book2', 2 )
insert into @book values(3, 'book3', 3 )

insert into @backupBook values(1, 'book1', 1 )
insert into @backupBook values(2, 'book2', 2 )

select * from @book
select * from @backupBook

delete a
from @book a 
INNER JOIN @backupBook b
  ON a.AuthorID = b.AuthorID
  and a.BookName = b.BookName
  and a.BookID = b.BookID

select * from @book
select * from @backupBook