如何选择没有适当键的行?

时间:2015-11-26 08:10:09

标签: sql-server-2008

以下是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

我需要从第一个表中选择所有行,其Value值不在Table2中。怎么做?

2 个答案:

答案 0 :(得分:0)

这样的东西?

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

答案 1 :(得分:0)

SELECT t1。* FROM @ Table1 t1 LEFT JOIN @ Table2 t2 ON t2.value = t1.value 在哪里t2.value IS NULL