首页 > 解决方案 > 在 Oracle 中替换 Minus、Union All、Intersect 运算符的替代方法

问题描述

我必须比较两个表中的数据。目前有一个存储过程,其中过程的逻辑是选择第一个表数据减去第二个表数据,反之亦然。如果计数匹配,则将消息硬编码为“匹配”,否则“无与伦比”

我的疑问:我可以用减号运算符以外的方式更改过程的逻辑吗?有什么建议么?

select count(*) into t1 from c1;
select count(*) into t2 from c2;
select count(*) into t3 from(
   select a1,a2,a3 from c1
      minus
     select a1,a2,a3 from c2);
select count(*) into t4 from(
     select a1,a2,a3 from c2
      minus
     select a1,a2,a3 from c1);

select count(*) into t5 from(
     select a1,a2,a3 from c2
      Intersect
     select a1,a2,a3 from c1);

Insert into A1 
SELECT t1,t2,t3,t4,t5,(CASE WHEN T4=0 THEN ‘MATCHED’
                                        ELSE ‘NOT MTACHED’
                                         END) STATUS ,’ ‘
FROM DUAL;

标签: oracleplsqlunion-allnested-queries

解决方案


从两个表中计算行数并使用minus两次似乎就足够了,我没想到会intersect发现新东西的场景。但是,在某些情况下,表不同并且您的查询显示MATCHED

with 
  t1(a1, a2, a3) as (
    select 1, 1, 1 from dual union all
    select 1, 1, 1 from dual union all
    select 2, 2, 2 from dual  ),
  t2(a1, a2, a3) as (
    select 1, 1, 1 from dual union all
    select 2, 2, 2 from dual union all
    select 2, 2, 2 from dual  )
select a1, a2, a3 from t1 intersect select a1, a2, a3 from t2 

两者都minus显示空结果,行数相等,相交显示 2 行,这没有告诉我们什么。这是与您的问题类似的问题,请在那里阅读答案。但是你需要对数据进行分组和计数,所以这会比你现在做的还要慢。

如果重复的行不是问题,那么彼得的答案看起来很有希望。


推荐阅读