【问题标题】:Select records from a table where two columns are not present in another table从另一个表中不存在两列的表中选择记录
【发布时间】:2016-06-21 19:53:30
【问题描述】:

我有表 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

还有一个 Table2:

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+Program 不在第二个表中的行。我正在使用 MS SQL Server express 2012,我不想在原始数据库中添加任何列。是否可以不创建临时变量?

【问题讨论】:

  • 你累了什么? not existsnot inouter join / null 检查——有很多方法可以做到这一点......
  • 没有。但是如何指定两列?

标签: sql sql-server tsql sql-server-2012


【解决方案1】:

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

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

【讨论】:

  • 您能解释一下 select 1 的作用吗?
  • @Morpheus -- not exists 不关心选择了哪个字段 -- 因此 select 1select *(不同于 not in)。这会产生一个correlated subquery——检查idprogram 是否已经存在。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2015-08-27
    • 1970-01-01
    • 2022-01-21
    • 2013-05-19
    • 1970-01-01
    • 2022-11-13
    • 1970-01-01
    • 2016-02-29
    相关资源
    最近更新 更多