2012-11-06 94 views
1

我已經使用內部連接加入了兩個表。這裏表TPREG的主鍵是co_idpol_id加入Db2查詢

SELECT (SELECT etbl_desc_txt 
     FROM uding604.tedit e 
     WHERE etbl_typ_id = 'PITCD' 
     AND co_id = 'CP' 
     AND etbl_valu_id = p.pol_ind_typ_cd) pol_ind_typ_cd, 
     (SELECT etbl_desc_txt 
     FROM uding604.tedit e 
     WHERE etbl_typ_id = 'PAYT' 
     AND co_id = 'CP' 
     AND etbl_valu_id = p.POL_BILL_TYP_CD) POL_BILL_TYP_CD, 
     POL_PAC_DRW_DY, 
     (SELECT etbl_desc_txt 
     FROM uding604.tedit e 
     WHERE etbl_typ_id = 'PAYM' 
     AND co_id = 'CP' 
     AND etbl_valu_id = p.POL_BILL_MODE_CD) POL_BILL_MODE_CD, 
     t.SOURCE_CD 
FROM uding604.tpol p, 
    uding604.TPREG t 
WHERE p.co_id = t.co_id 
AND p.pol_id = t.pol_id 
AND p.co_id = 'CP' 
AND p.pol_id = '000000011' 
AND t.co_id = 'CP' 
AND t.pol_id = '000000011' 

如何讓這個查詢更簡單嗎?

請指導。

回答

2

您可以將子查詢轉換爲連接:.

SELECT e1.etbl_desc_txt as pol_ind_typ_cd, 
     e2.etbl_desc_txt as POL_BILL_TYP_CD, 
     POL_PAC_DRW_DY, 
     e3etbl_desc_txt as POL_BILL_MODE_CD, 
     t.SOURCE_CD 
FROM uding604.tpol p, 
    uding604.TPREG t, 
    uding604.tedit e1, 
    uding604.tedit e2, 
    uding604.tedit e3 
WHERE p.co_id = t.co_id 
AND p.pol_id = t.pol_id 
AND p.co_id = 'CP' 
AND p.pol_id = '000000011' 
AND t.co_id = 'CP' 
AND t.pol_id = '000000011' 
AND e1.etbl_typ_id = 'PITCD' 
AND e1.co_id = 'CP' 
AND e1.etbl_valu_id = p.pol_ind_typ_cd 
AND e2.etbl_typ_id = 'PAYT' 
AND e2.co_id = 'CP' 
AND e2.etbl_valu_id = p.POL_BILL_TYP_CD 
AND e3.etbl_typ_id = 'PAYM' 
AND e3.co_id = 'CP' 
AND e3.etbl_valu_id = p.POL_BILL_MODE_CD 

查詢是select條款更清晰,但在模糊的條款Where

我們所能做的就是在ANSI移動JOIN語法:

SELECT e1.etbl_desc_txt as pol_ind_typ_cd, 
     e2.etbl_desc_txt as POL_BILL_TYP_CD, 
     POL_PAC_DRW_DY, 
     e3etbl_desc_txt as POL_BILL_MODE_CD, 
     t.SOURCE_CD 
FROM uding604.tpol p 
JOIN uding604.TPREG t on (p.co_id = t.co_id AND p.pol_id = t.pol_id) 
JOIN uding604.tedit e1 on (e1.etbl_valu_id = p.pol_ind_typ_cd and e1.co_id = p.co_id) 
JOIN uding604.tedit e2 on (e2.etbl_valu_id = p.POL_BILL_TYP_CD and e2.co_id = p.co_id) 
JOIN uding604.tedit e3 on (e3.etbl_valu_id = p.POL_BILL_MODE_CD and e3.co_id = p.co_id) 
WHERE p.co_id = 'CP' 
AND p.pol_id = '000000011' 
AND t.co_id = 'CP' 
AND t.pol_id = '000000011' 
AND e1.etbl_typ_id = 'PITCD' 
AND e2.etbl_typ_id = 'PAYT' 
AND e3.etbl_typ_id = 'PAYM' 

現在更清楚你想要什麼。

注1。您可能會嘗試刪除

AND t.co_id = 'CP' 
AND t.pol_id = '000000011' 

因爲不是邏輯必要的。

注2。您必須測試這些查詢是否與您的查詢一樣返回。

注3。你應該總是使用ANSI JOIN語法,當你不期待它時會幫助你。