我有两个表:tableA 和 tableB。如何获取 tableA 中但不在 tableB 中的所有记录?我对执行此操作的正确方法感兴趣,而不是解决方法。我尝试使用左连接,然后添加where ID is not null
. 它有效,但我不确定这是否是正确的方法。
问问题
1967 次
5 回答
3
select * from tableA
where id not in (select id from tableB)
或者
select * from tableA a
left join tableB b on a.id = b.id
where b.id is null
两者都是完全可以接受的检索您所问内容的方法。
于 2012-08-06T17:10:10.757 回答
0
Sql 小提琴 [][1]
演示 http://www.sqlfiddle.com/#!3/10300/2
select * from table1 where id not in(select id from table2)
于 2012-08-06T17:20:35.463 回答
0
您可以使用NOT EXISTS
. 我更喜欢使用NOT EXISTS
,因为当列允许空值但没有空值时,NOT IN
性能明显比NOT EXISTS
.
Select * from table1 a
Where not exists (Select ID from table2 b where a.ID = b.ID)
在non-nullable
列上,您可以使用适合您情况的任何一种,因为NOT IN
和 NOT EXISTS 的行为和性能是相同的。
于 2012-08-06T17:16:25.003 回答
0
由于您没有给出表模式,因此假设每个 table.id1,id2 中都有主键
你可以在左连接的帮助下做。
Select * from table1 left join table2 where id2 is null
注意这不是一个实际的查询,只是提示您继续。
于 2012-08-06T17:36:22.143 回答
0
如果您需要在页面上显示数据(编程),您必须为此使用连接,如果您需要将数据从一个表移动到另一个表以进行备份或其他类似目的,则需要一个 sql 比较工具。首先,您需要 sql left join。将您的表 A 设为左表并与 B 一起放置并加入
select * from A
left join B on A.id = B.id
where b.id is null
于 2012-08-06T17:12:49.457 回答