SQL:如何使用CASE提高INNER JOIN的性能

时间:2017-10-19 07:47:10

标签: sql-server performance inner-join hana

对于需要读取过滤器的过滤器表并读取与该过滤器相关的源数据表的查询,我遇到了很大的性能问题。 所以我的过滤器表看起来像这样;

FILTER_ID CUSTOMER COUNTRY DEPARTMENT
   1                  UK      DEP1
   2       CUS1       US      DEP1
   3       CUS1  

这是我的源数据表;

ROW_NO CUSTOMER COUNTRY DEPARTMENT
  1      CUS1     UK      DEP1
  2      CUS2     UK      DEP1
  3      CUS3     UK      DEP1
  4      CUS1     US      DEP1
  5      CUS1     SG      DEP3
  6      CUS1     UK      DEP3

对于过滤器表上的每个过滤器,我需要从源数据表中获取行。但是如果FILTER表上的列是EMPTY,我们需要读取源数据表中存在的该列的所有成员。假设对于FILTER_ID 1,我们需要从源表中读取COUNTRY = UK和DEPARTMENT = DEP1的所有客户。

这就是结果表的样子;

FILTER_ID   ROW_NO   CUSTOMER   COUNTRY   DEPARTMENT
   1           1       CUS1       UK        DEP1
   1           2       CUS2       UK        DEP1
   1           3       CUS3       UK        DEP1
   2           4       CUS1       US        DEP1
   3           1       CUS1       UK        DEP1
   3           4       CUS1       US        DEP1
   3           5       CUS1       SG        DEP3
   3           6       CUS1       UK        DEP3

我正在使用条件连接,它工作正常,但问题是,它非常慢!

select t1.FILTER_ID, t2.* from FILTER_TABLE as t1
inner join SOURCE_DATA as t2 on 
CASE WHEN t1.CUSTOMER    = '' THEN t2.CUSTOMER   ELSE t1.CUSTOMER END = t2.CUSTOMER and
CASE WHEN t1.DEPARTMENT  = '' THEN t2.DEPARTMENT ELSE t1.DEPARTMENT END = t2.DEPARTMENT and
CASE WHEN t1.COUNTRY     = '' THEN t2.COUNTRY    ELSE t1.COUNTRY END = t2.COUNTRY 

有没有办法优化此代码?

2 个答案:

答案 0 :(得分:0)

尝试这样,我想,它会很快:

select t1.FILTER_ID, t2.* from FILTER_TABLE as t1
inner join SOURCE_DATA as t2 on 
 t1.CUSTOMER    = t2.CUSTOMER and
 t1.DEPARTMENT  = t2.DEPARTMENT and
 t1.COUNTRY     = t2.COUNTRY 
where t1.CUSTOMER <> '' and t1.DEPARTMENT <>'' and t1.COUNTRY <> ''
union all
select t1.FILTER_ID, t2.* from FILTER_TABLE as t1
inner join SOURCE_DATA as t2 on 
CASE WHEN t2.CUSTOMER    = t2.CUSTOMER 
where t1.CUSTOMER = '' and t1.DEPARTMENT <>'' and t1.COUNTRY <> ''
union all
select t1.FILTER_ID, t2.* from FILTER_TABLE as t1
inner join SOURCE_DATA as t2 on 
CASE WHEN t2.DEPARTMENT    = t2.DEPARTMENT 
where t1.CUSTOMER <> '' and t1.DEPARTMENT = '' and t1.COUNTRY <> ''
union all
select t1.FILTER_ID, t2.* from FILTER_TABLE as t1
inner join SOURCE_DATA as t2 on 
CASE WHEN t2.COUNTRY    = t2.COUNTRY 
where t1.CUSTOMER <> '' and t1.DEPARTMENT <> '' and t1.COUNTRY = ''

答案 1 :(得分:0)

尝试这样:

select t1.FILTER_ID, t2.* from FILTER_TABLE as t1
inner join SOURCE_DATA as t2 on 
 IIF(t1.CUSTOMER = '',t2.CUSTOMER, t1.CUSTOMER)  = t2.CUSTOMER and
 IIF(t1.DEPARTMENT = '', t2.DEPARTMENT,t1.DEPARTMENT) = t2.DEPARTMENT  and
 IIF(t1.COUNTRY = '',t1.COUNTRY,t2.COUNTRY) = t2.COUNTRY