2010-01-12 155 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