0

我正在尝试将行从 1 个表复制到其自身的副本,但仅包括存在于第二个表中的帐户的行。

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

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)

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

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

我知道我可以通过连接来做到这一点,但是我必须指定所有列(可能很多 - 我有几个表的这种情况)。

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

4

2 回答 2

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
)
于 2016-02-11T12:51:22.793 回答
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
                  );
于 2016-02-11T12:26:25.233 回答