排除两个表匹配的记录sql

时间:2016-02-10 11:25:04

标签: sql

它不是另一个问题的副本,因为我有两个表,当内部加入时,t-numbers应该排除搜索条件,我不能在搜索条件上使用distinct。

我有两张桌子

表A:

T_ref            t_number
VC04706610      1369473
VC0484351A      1357916 
VC04882679      1311572

表B:

t_number  thr_hold_type
1369473    2877417
1369473    2877657
1357916    2877417
1357916    2877635
1357916    2877697
1311572    2877637
1311572    2877572

我想要排除持有类型2877417的记录。

查询:

SELECT t_ref
 FROM table a
 INNER JOIN table b
     ON b.t_number = a.t_number
 WHERE thr_hold_type NOT IN ('2877417') 
     AND t_reference IN ( 'VC04706610', 'VC0484351A',b'VC04882679', 'VC04885203')

当我运行此查询时,它会调出所有其他保持类型,我想完全排除这些具有该保持类型的t_references ..

3 个答案:

答案 0 :(得分:0)

你试过这个简单的事吗:

     SELECT *
     FROM  tableA
     JOIN tableB 
     ON tableA.t_number = tableB.t_number
     WHERE thr_hold_type != 287741

答案 1 :(得分:-1)

试试这个:

select t_ref from TableA a
where a.t_number not in
  (select b.t_number from TableB b where b.thr_hold_type = '2877417')

答案 2 :(得分:-1)

嗨bellow查询应该工作,你的数据中有数据重复可能会产生问题,你也可以使用exists子句而不是内连接。

with a as
( select 'VC04706610' t_ref,  1369473 t_number from dual
union
select 'VC0484351A' t_ref,  1357916 t_number from dual
union
select 'VC04882679' t_ref,  1311572 t_number from dual
),
b as
(
select 1369473 t_number,   2877417 thr_hold_type from dual
union
select 1369473 t_number,   2877657 thr_hold_type from dual
union
select 1357916 t_number,   2877417 thr_hold_type from dual
union
select 1311572 t_number,   2877637 thr_hold_type from dual
union
select 1311572 t_number,   2877572 thr_hold_type from dual
)
select * from a inner join b on a.t_number = b.t_number
and thr_hold_type <> 2877417
and t_ref in ('VC04706610',
'VC0484351A',
'VC04885203')