2015-11-26 25 views
0

這裏有2個表:如何選擇沒有適當的鍵的行?

declare @Table1 table (ID int NOT NULL PRIMARY KEY, Value int) 
declare @Table2 table (ID int NOT NULL PRIMARY KEY, Value int) 

insert into @Table1 (ID, Value) 
select 1, 100 
union all 
select 2, 101 
union all 
select 3, 103 
union all 
select 4, 104 
union all 
select 5, 105 

insert into @Table2 (ID, Value) 
select 1, 100 
union all 
select 2, 110 
union all 
select 3, 111 

我需要從第一個表中的所有行,它的價值的價值觀是不是在表2。怎麼做?

回答

0

這樣的事情?

Select * from Table1 where value not in(select distinct value from table2) 
+0

如果在什麼第二個表某些值爲NULL? – tesicg

+0

這不是新問題,因爲如果Value的值爲NULL,則上部查詢不起作用。 – tesicg

+1

本文可能有所幫助:[鏈接](http://stackoverflow.com/questions/2686254/how-to-select-all-records-from-one-table-that-do-not-exist-in-another-表) – Nemeas

0

SELECT T1。* FROM 表1 @ T1 LEFT JOIN表2 @ T2 ON t2.value = t1.value WHERE t2.value IS NULL

相關問題