Sql 从另一个表中不存在两列的表中选择记录
我有表1:Sql 从另一个表中不存在两列的表中选择记录,sql,sql-server,tsql,sql-server-2012,Sql,Sql Server,Tsql,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 表2: ID Program BestBefore 12345 ABC 2 12345 FG
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,不想向原始数据库添加任何列。可以不创建临时变量吗?有几种方法可以做到这一点,这里有一种方法是使用
不存在:
select *
from table1 t1
where not exists (
select 1
from table2 t2
where t1.id = t2.id and t1.program = t2.program
)
一种可能的变体是使用左连接
:
SELECT
Table1.*
FROM
Table1
LEFT JOIN Table2
ON Table1.ID = Table2.ID
AND Table1.Program = Table2.Program
WHERE
Table2.ID IS NULL
你累了什么<代码>不存在
,不在
,外部连接/null
检查--有很多方法可以做到这一点…不在。但是如何指定两列?您能解释一下select 1的作用吗?@Morpheus--不存在
不关心选择了哪个字段--因此select 1
或select*
(不同于不在
中)。这将生成一个相关子查询
——检查id
和程序
是否已经存在。