1

我已经使用内连接连接了两个表。这里表的主键TPREGco_idpol_id

 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'

如何使这个查询更简单?

请指导。

4

1 回答 1

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 语法,它会在您意想不到的时候帮助您。

于 2012-11-06T07:05:07.313 回答