2010-01-12 142 views
1

我怎样才能得到第一个表中的所有记录不存在于第二个表中而不使用子查询? 我想用加入...SQL查询:不使用子查询

+0

请注意,'LEFT JOIN/IS NULL'与“NOT EXISTS”或“NOT IN”不一样:http://explainextended.com/2009/09/15/not-in-vs -not-exists-vs-left-join-is-null-sql-server/ – 2010-01-12 06:04:26

回答

2
SELECT A.someColumn 
FROM A LEFT JOIN B 
ON A.ID = B.ID 
WHERE B.ID IS NULL 
+0

感谢您的快速回复。我只是忘记了几个连接的概念。感谢提醒... – Shivkant 2010-01-12 06:34:06

2

你甚至可以使用

一)EXCEPT

B)Where Not in

例如 示例数据

declare @t1 table(id1 int, recordsA varchar(20)) 
insert into @t1 
select 1,'record1' union all 
select 2,'record2' union all 
select 3,'record3' union all 
select 4,'record4' union all 
select 5,'record5' 

declare @t2 table(id2 int, recordsB varchar(20)) 
insert into @t2 
select 1,'record1' union all 
select 2,'record2' union all 
select 3,'record3' 

查询:1

select t1.id1,t1.recordsA from @t1 t1 
except 
select t2.id2,t2.recordsB from @t2 t2 

问题2:

select t1.id1,t1.recordsA from @t1 t1 
where t1.recordsA not in(select t2.recordsB from @t2 t2) 

输出:

id1 recordsA 
4 record4 
5 record5