Oracle中的变量排除表?

时间:2016-04-04 13:37:54

标签: sql database oracle lookup

很抱歉,如果这个解释在任何方面都不清楚。我在Oracle工作。

我有一个大表,其中包含Country,Division,SubDivision,SpendCategory等列。我需要为这个大表创建每个国家的可能灵活的排除标准,并考虑创建第二个'排除表“就这样。

 CREATE TABLE EXCLUSIONS

 (COUNTRY VARCHAR(50), EXCLUSIONFIELD VARCHAR(50), FIELDVALUE VARCHAR(50));

我的想法是我可以用

这样的行填充此表
 Mexico - Division - "Central Division"

 Mexico - SubDivision - "Mexico City"

 France - Division - "Paris Division"
  

...

     

使用此表,自动过滤我的表以排除数据   where(country = Mexico AND division =“central division”),   (country = Mexico AND subdivision =“Mexico City”),(country = France AND   division =“paris division”),

...

所以我想我有两个问题。首先,这是最好的方法吗?我喜欢这个想法,因为排除列表可能很长,并且让第三方维护表似乎比手动更新大量where条件更可行。其次,如何编写查询以从主表中排除Exclusions表中的所有条件?

2 个答案:

答案 0 :(得分:3)

您正在做什么可以工作,但查询将如下所示:

select t.*
from t
where not exists (select 1
                  from exclusions e
                  where e.exclusionfield = 'country' and e.value = t.country or
                        e.exclusionfield = 'district' and e.value = t.district or
                        . . .
                  );

这可能是一个非常难以优化的查询。您可能希望使用单独的子查询来表达它:

select t.*
from t
where not exists (select 1
                  from exclusions e
                  where e.exclusionfield = 'country' and e.value = t.country 
                 ) or
      not exists (select 1

来自排除项目e                       其中e.exclusionfield ='district'和e.value = t.district                      );

您应该能够使用exclusions(value, exclusionfield)上的索引获得合理的效果。

另一种方法是复制列。 。 。 countrydistrict等,删除exclusionfield列:

select t.*
from t
where exists (select 1
              from exclusions e
              from e.country = t.country or
                   e.district = t.district or
                   . . .
             );

使用单独的exists子查询也可以更好地优化。

答案 1 :(得分:0)

要排除您可以使用的数据不存在(从condition_table中选择1,其中......)
你也可以使用条件(国家,细分)而不是(....)
要使用某些数据过滤select,可以在select ...

之前使用'with'子句动态定义表