首页 > 解决方案 > 如果另一个表中存在一个行 ID,则跳过所有行

问题描述

我有三个具有这种关系的表:

T1.journo = T2.journo
T2.recid = T3.spid

        T1
ticketno  journo
   1        A1
   2        A2

    T2
journo recid
  A1    1
  A1    2
  A1    3
  A2    4
  A2    5
  A2    6


 T3
spid
 2

我只想要 T3.spid 中不存在 T2.recid 的 T1 条目。

下面的查询将省略 T2 的第二行。但是我希望省略 journo=A1 的所有 T2 行,因为 T3 中存在 A1 的一个记录。

 select T1.* from T1 join T2 on T1.journo = T2.journo
 where T2.recid not in (select spid from T3)

期望的输出:

ticketno journo
   2       A2

有小费吗?

标签: sqlsql-serversql-server-2012

解决方案


对我来说,这听起来像not exists

select t1.*
from t1
where not exists (select 1
                  from t2 join
                       t3
                       on t2.recid = t3.spid
                  where t2.journo = t1.journo
                 );

推荐阅读