DB2 z / os sql中的混合连接

时间:2014-12-01 02:34:07

标签: sql db2-400 ibm-db2

我一直在重写几十年前的数据库z / OS查询,有三个表格如下:

客户

+-----------+----------+---------+
|customer_id|state_code|city_code|
+-----------+----------+---------+

customer_address

+-----------+-------------+
|customer_id|facility_name|
+-----------+-------------+

贷款

+-----------+----------+---------+
|loan_code  |state_code|city_code|
+-----------+----------+---------+

customer = customer_address是一对一的,customer = loan是一对多的。

我们过去常常有两个不同的查询来获取按州和城市划分的客户名单,他们有贷款并且在商业活动中活跃于" (通过在customer_address中记录!)如下所示:

SELECT CUST.STATE_CODE, CUST.CITY_CODE, CUST_ADRS.FAC_NAME 
FROM  CUSTOMER CUST, CUST_ADDRESS WHERE CUST_ADRS.ADR_ID <> 0 AND      
CUST_ADRS.CUST_ID = CUST.CUST_ID

收集上述查询的结果,并将每个州和城市从PreparedStatement传递到以下查询。如果存在loan_id,则我们收集州,城市和设施名称。

SELECT CL.LOAN_ID FROM CUSTOMER_LOAN CL WHERE
CL.LOAN_CODE IN ('A1', 'BC') AND CL.STATE_CODE = ? AND CL.CITY_CODE = ?

我已将这两个查询重写为单个查询。 (customer.cust_id,customer_loan.loan_id有适当的索引)。我没有在修改后的查询中包含loan_id。

SELECT DISTINCT CUST.STATE_CODE, CUST.CITY_CODE, CUST_ADRS.FAC_NAME
FROM CUSTOMER CUST INNER JOIN CUST_ADDRESS CUST_ADRS ON 
CUST_ADRS.ADR_ID <> 0 AND CUST.CUST_ID = CUST_ADRS.CUST_ID
INNER JOIN CUSTOMER_LOAN CL
ON 
CL.LOAN_CODE IN ('A1', 'BC') and
CL.STATE_CODE = CUST.STATE_CODE and
CL.CITY_CODE = CUST.CITY_CODE

现在我可以看到Web应用程序的性能得到了显着提升,查询执行时间大约需要700毫秒。但我想知道我能做些什么来改进或修改这个查询。任何意见或想法都非常感谢。

1 个答案:

答案 0 :(得分:1)

可能更快的一个选项是使用EXISTS

select c.state_code, c.city_code, ca.fac_name
from customer c 
    join customer_address ca on c.customer_id = ca.customer_id 
where exists (
    select 1
    from loan l
    where l.state_code = c.state_code and
          l.city_code = c.city_code and
          l.loan_code in ('A1','BC')
    )

与往常一样,您需要自己测试每个查询,以查看哪个表现最佳。