2016-03-08 111 views
1

我有表1:从表中选择记录,其中两列不存在于另一个表

Id  Program Price Age 
12345 ABC  10  1 
12345 CDE  23  3 
12345 FGH  43  2 
12346 ABC  5  4 
12346 CDE  2  5 
12367 CDE  10  6 

和表2:

ID  Program BestBefore 
12345 ABC  2 
12345 FGH  3 
12346 ABC  1 

我想在下表中,

Id  Program Price Age 
12345 CDE  10  1 
12346 CDE  2  5 
12367 CDE  10  6 

即得到第一个表中ID +程序不在第二个表中的行。我正在使用MS SQL Server Express 2012,我不想将任何列添加到原始数据库。是否可以不创建临时变量?

+0

你有什么累了吗? '不存在','不在','外部连接/空'检查 - 很多方法来做到这一点... – sgeddes

+0

不在。但如何指定两列? – Morpheus

回答

2

几种方法可以做到这一点,这里有一个使用not exists

select * 
from table1 t1 
where not exists (
    select 1 
    from table2 t2 
    where t1.id = t2.id and t1.program = t2.program 
) 
+0

你能否请求解释选择1做什么? – Morpheus

+1

@Morpheus - 'not exists'不关心选择哪个字段 - 因此'选择1'或'select *'(不同于'not in')。这会产生一个“相关的子查询” - 检查已经存在的'id'和'program'。 – sgeddes

1

一个可能的变化是使用LEFT JOIN

SELECT 
    Table1.* 
FROM 
    Table1 
    LEFT JOIN Table2 
     ON Table1.ID = Table2.ID 
     AND Table1.Program = Table2.Program 
WHERE 
    Table2.ID IS NULL 
相关问题