从一个表中选择记录,而另一个表中没有两列

Mor*_*eus 4 sql t-sql sql-server sql-server-2012

我有表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
Run Code Online (Sandbox Code Playgroud)

和一个Table2:

ID      Program BestBefore
12345   ABC     2
12345   FGH     3
12346   ABC     1
Run Code Online (Sandbox Code Playgroud)

我想得到下表

Id      Program  Price  Age
12345   CDE      10     1
12346   CDE      2      5
12367   CDE      10     6
Run Code Online (Sandbox Code Playgroud)

即从第一张表中获取ID + Program不在第二张表中的行。我正在使用MS SQL Server Express 2012,并且不想将任何列添加到原始数据库。是否可以不创建临时变量而做?

sge*_*des 7

有几种方法可以使用,这是一种使用方法not exists

select *
from table1 t1
where not exists (
    select 1
    from table2 t2 
    where t1.id = t2.id and t1.program = t2.program
)
Run Code Online (Sandbox Code Playgroud)

  • @Morpheus——“不存在”不关心选择了什么字段——因此“选择1”或“选择*”(与“不在”不同)。这会产生一个“相关子查询”——检查已经存在的“id”和“程序”。 (2认同)

Vla*_*nov 6

一种可能的变体是使用LEFT JOIN

SELECT
    Table1.*
FROM
    Table1
    LEFT JOIN Table2
        ON  Table1.ID = Table2.ID
        AND Table1.Program = Table2.Program
WHERE
    Table2.ID IS NULL
Run Code Online (Sandbox Code Playgroud)