SQL 2在同一个表上保留外连接

时间:2011-07-14 14:46:17

标签: sql join left-join outer-join

我在同一张桌子上做2个连接,我想要以下结果:

chnl_ptnr_key type1_ky type2_ky
------------- -------- --------
1             1        null
1             2        null
1             null     3
1             null     4

但相反,我正在

chnl_ptnr_key type1_ky type2_ky
------------- -------- --------
1             1        3
1             2        3
1             2        3
1             2        4

我的查询是:

SELECT cp.chnl_ptnr_ky, cpmap1.ky as type1_ky, cpmap2.ky as type2_ky
FROM chnl_ptnr cp
LEFT OUTER JOIN chnl_ptnr_oos_map cpmap1 on (cp.chnl_ptnr_ky = cpmap1.chnl_ptnr_ky and cpmap1.typ = 'TYPE1')
LEFT OUTER JOIN chnl_ptnr_oos_map cpmap2 on (cp.chnl_ptnr_ky = cpmap2.chnl_ptnr_ky and cpmap2.typ = 'TYPE2')
WHERE cp.chnl_ptnr_ky = '1111'

有人可以帮助我更改此查询,以便在type1_kytype2_ky中从其他联接返回行时获取空值吗? 我需要这种格式,因为我试图将它用于iBATIS地图。

非常感谢

1 个答案:

答案 0 :(得分:2)

在您的示例中,第一个LEFT JOIN的结果是(1,1)和(1,2)。由于没有(1,NULL)记录,在下一个LEFT JOIN之后将没有(1,NULL,?)记录。

你可能在某处需要一个UNION ......

SELECT  cp.chnl_ptnr_ky, cpmap1.ky as type1_ky,  NULL AS type2_ky
FROM chnl_ptnr cp
LEFT OUTER JOIN chnl_ptnr_oos_map cpmap1 on (cp.chnl_ptnr_ky = cpmap1.chnl_ptnr_ky and     cpmap1.typ = 'TYPE1')
WHERE cp.chnl_ptnr_ky = '1111'

UNION ALL

SELECT  cp.chnl_ptnr_ky, NULL,  cpmap2.ky as type2_ky
FROM chnl_ptnr cp
LEFT OUTER JOIN chnl_ptnr_oos_map cpmap2 on (cp.chnl_ptnr_ky = cpmap2.chnl_ptnr_ky   and      cpmap2.typ = 'TYPE2')
WHERE cp.chnl_ptnr_ky = '1111'