如何获取表A中的记录,这些记录在表B中的一行中

时间:2018-04-09 10:30:29

标签: sql

SELECT ClaimID, CPTCode FROM TABLEA

ClaimId CPTCode
  **60  62000**
  **60  0213T**
  60    99383
  60    93230
  60    96372

SELECT cpt1,CPT2 FROM TABLEB

cpt1    CPT2
**62000 0213T**
**62000 0230T**
62000   0216T
62000   0228T

从tableA中仅选择tableB中同一行的记录 结果应该是

60  62000
60  0213T

2 个答案:

答案 0 :(得分:0)

我认为这可以满足您的需求:

select ClaimID, CPTCode 
from tablea a
where exists (select 1
              from tableb b
              where b.cpt1 = a.cptcode
             ) or
      exists (select 1
              from tableb b
              where b.cpt2 = a.cptcode
             );

此查询可以利用两个索引:tableb(cpt1)tableb(cpt2)

您可以将其写为:

select ClaimID, CPTCode 
from tablea a
where exists (select 1
              from tableb b
              where a.cptcode in (b.cpt1, b.cpt2)
             );

但是,这个版本更难以优化。

答案 1 :(得分:0)

试试这个 -

select obj.ClaimID, obj.CPTCode from (
select row_number() as row_noA, ClaimID, CPTCode FROM TABLEA
join 
select row_number() as row_noB, cpt1,CPT2 FROM TABLEB
on TABLEA.CPTCode = TABLEB.CPT2 and TABLEA.row_noA = TABLEB.row_noB
)obj

连接两个表并使用相同的行号匹配每一行并获取输出