首页 > 解决方案 > Oracle 连接到多个列中的任何一个

问题描述

我有一个关系表

NUM1 | NUM2 | NUM3
 --   ---   -----
 1     2     3    
 2     4     5
 3     4     null
 3     4     null

以及 NUM 是主键的实际 INFO 表。

 NUM | A_LOT_OF_OTHER_INFO
 ---  --------------------
   1     asdff    
   2     werwr
   3     erert
   4     ghfgh
   5     cvbcb

我想创建一个视图来查看出现在 RELATION 表的 NUM1、NUM2、NUM3 中的任何一个中的 NUM 的计数。

我的观点

 NUM | A_LOT_OF_OTHER_INFO | TOTAL_COUNT
 ---  --------------------  ------------
   1     asdff                  1
   2     werwr                  2
   3     erert                  3
   4     ghfgh                  3
   5     cvbcb                  1

我可以通过从 RELATION 表中选择三个并将它们 UNION 来做到这一点,但我不想使用 UNION 因为表有很多记录,MY_VIEW 已经足够大,我正在寻找一种更好的方法来加入 RELATION视图中的表。你能建议一个方法吗?

标签: sqloracle

解决方案


我会建议一个相关的子查询:

select i.*,
       (select ((case when r.num1 = i.num then 1 else 0 end) +
                (case when r.num2 = i.num then 1 else 0 end) +
                (case when r.num3 = i.num then 1 else 0 end)
               )
        from relation r
        where i.num in (r.num1, r.num2, r.num3)
       ) as total_count
from info i;

如果考虑性能,使用left joins 可能会更快:

select i.*,
       ((case when r1.num1 is not null then 1 else 0 end) +
        (case when r2.num1 is not null then 1 else 0 end) +
        (case when r3.num1 is not null then 1 else 0 end)
       ) as total_count
from info i left join
     relation r1
     on i.num = r1.num1 left join
     relation r2
     on i.num = r2.num2 left join
     relation r3
     on i.num = r3.num3;

特别是,这将优化使用relation: relation(num1)relation(num2)和上的三个独立索引relation(num3)


推荐阅读