Sql SubSelect With Multiple Keys

时间:2016-02-11 12:18:15

标签: sql db2 db2-400 sql-subselect

我正在尝试将行从1个表复制到自身的副本,但只包含第2个表中存在的帐户的行。

这只适用于一个关键字段(帐户),如下所示:

insert into newlibr.acpmstpf
select * from oldlibr.acpmstpf as source
where not exists
(select *
 from newlibr.acpmstpf as target
 where target.acpno    = source.acpno
   and target.acpbrn   = source.acpbrn
   and target.acpitm   = source.acpitm)
 and source.acpno in (select account from accinfo)

在这种情况下,我试图将schema oldlibr中的原始表acpmstpf中的行插入newlibr中的自身副本,匹配2键帐户/分支(acpno / acpbrn)上的行,并且仅将这些行插入帐户在第二表accinfo。

我真正想要做的是只将那些行插入帐户& branch在accinfo中,因为如果只有2个分支在accinfo中,并且acpmstpf上有100个,它会复制所有100行。

我知道我可以通过连接执行此操作,但之后我必须指定所有列(可能很多 - 我有几个表的这种情况)。

有没有办法可以做到这一点,仍然使用子选择?

2 个答案:

答案 0 :(得分:2)

您想要替换

and source.acpno in (select account from accinfo)

并寻找元组(帐户,分支)。许多DBMS都支持这一点:

and (source.acpno, source.acpbrn) in (select account, branch from accinfo)

对于那些没有的DBMS,您必须诉诸EXISTS

and exists
(
  select * 
  from accinfo
  where accinfo.account = source.acpno
    and accinfo.branch = source.branch
)

答案 1 :(得分:1)

使用exists

insert into newlibr.acpmstpf
    select *
    from oldlibr.acpmstpf as source
    where not exists (select 1
                      from newlibr.acpmstpf as target
                      where target.acpno = source.acpno and
                            target.acpbrn = source.acpbrn
                            target.acpitm = source.acpitm
                     ) and
           exists (select 1
                   from accinfo a
                   where source.acpno = a.accinfo and
                         source.acpbrn = a.acpbrn
                  );