如果另一张表中存在一个行ID,则跳过所有行

时间:2018-06-26 13:02:21

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

我有三个与此相关的表:

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的Recid。

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

所需的输出:

ticketno journo
   2       A2

有什么提示吗?

7 个答案:

答案 0 :(得分:2)

对我来说,这听起来像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
                 );

答案 1 :(得分:1)

应该能够在子查询中不使用。

declare @t1 table (ticketno int identity(1,1), journo varchar(2))

declare @t2 table (journo varchar(2), recid int identity(1,1))

declare @t3 table (spid int)

insert into @t1
values
('A1'),
('A2')

insert into @t2
values
('A1'),
('A1'),
('A1'),
('A2'),
('A2'),
('A2')

insert into @t3
values
(2)


select T1.* , T2.*
from @t1 T1 
inner join @t2 T2 on T1.journo = T2.journo
where T2.journo not in (select t22.journo from @t2 t22 where t22.recid in (select * from @t3))

或者,不存在相关

where not exists(select t22.journo from  @t2 t22 where t22.recid in (select * from @t3) and t22.journo = T2.journo)

答案 2 :(得分:1)

在T3上加入T2,并保持左连接。然后对t1变量进行分组,然后检查COUNT(t3.spid)= 0。 任何空值都不应计算在内,因此计数为零就是您想要的。

SELECT t1.*
FROM @t1 t1
JOIN @t2 t2 ON t2.journo = t1.journo
LEFT JOIN @t3 t3 ON t3.spid = t2.recid
GROUP BY t1.ticketno, t1.journo
HAVING COUNT(t3.spid) = 0

答案 3 :(得分:1)

SQL,这是我们生活中丑陋但必不可少的部分:

SELECT * FROM T1
INNER JOIN
(SELECT a1.journo
, SUM(spid_present) AS 'total_spids'
    FROM
        (SELECT T2.journo
        , T2.ticketno
        , CASE
            WHEN t3.spid IS NOT NULL
            THEN 1
            ELSE 0
            END AS 'spid_present'
        FROM T2
        LEFT JOIN T3
        ON T2.recid = T3.spid) a1
GROUP BY a1.journo) a2
    ON T1.journo = a2.journo
    AND a2.total_spids = 0}

答案 4 :(得分:1)

使用除:

    create table t1 (ticketno int, journo char(2))
    insert into t1 values (1, 'A1'), (2, 'A2')

    create table t2 (journo char(2), recid int)
    insert into t2 values ('A1', 1), ('A1', 2), ('A1', 3), ('A2', 4), ('A2', 5), ('A2', 6)

    create table t3 ([SPID] int)
    insert into t3 values (2)

    select t1.* from t1 
    except 
    select t1.*  
    from t1 
    inner join t2 on t2.journo = t1.journo 
    inner join t3 on t2.recid = t3.[SPID]

答案 5 :(得分:0)

您可以尝试以下SQL查询。

select T.* from T1 , T2 a where T1.journo = a.journo and a.recid not exists (select 1 from T3, T2 where T2.recid= T3.spid and T2.recid =a.reci);

答案 6 :(得分:0)

据我了解,简单加入

select t1.* from #t1 t1
join #t2 t2
on t1.journo <> t2.journo
join #t3 t3
on t2.recid = t3.spid