使用第三个表链接两个表,其中第二个表与第一个表中的一个条目相关

时间:2013-11-24 11:45:26

标签: sql oracle left-join

这可能已经回答了,但我找不到任何东西。

在我的Oracle DB中,我有两个表

S_PIPE_N

G3E_ID  |G3E_FID
380     |  1181024
2064    |  1188176

S_PCONPT_N

G3E_ID| G3E_FID| BOTTOM_HEIGHT
783   | 1181025| 253.4
4173  | 1188175| 364.51
4174  | 1188178| 366.76
17106 | 1379384| 253.11

和连接这两个

的表格

S_MANY_PCP_N

G3E_ID | G3E_FID | G3E_OWNERFID |G3E_CID
2539   | 1181025 | 1181024      |1
68507  | 1379384 | 1181024      |2
15444  | 1188178 | 1188176      |1
15448  | 1188175 | 1188176      |2

我想得到以下select语句的结果:

C.g3e_fid | A.bottom_height_1 | D.bottom_height_2
1181024   | 253.4             | 253.11
1188176   | 366.76            | 364.51

我尝试了以下声明:

select C.G3E_FID, A.BOTTOM_HEIGHT AS "bottom_height_1", D.BOTTOM_HEIGHT "bottom_height_2" FROM S_PIPE_N C, S_MANY_PCP_N B LEFT OUTER JOIN S_PCONPT_N A ON A.G3E_FID=B.G3E_FID AND B.G3E_CID=1 LEFT OUTER JOIN S_PCONPT_N D ON A.G3E_FID=D.G3E_FID AND B.G3E_CID=2 WHERE C.G3E_FID=B.G3E_OWNERFID

虽然这样我得到以下内容:

C.g3e_fid | A.bottom_height_1 | D.bottom_height_2
1181024   | 253.4             | null
1181024   |null | 253.11
1188176   | 366.76            | null
1188176   | null           | 364.51

如何更改每g3e_fid只获得一个结果的语句

3 个答案:

答案 0 :(得分:1)

这应该有效

select C.G3E_FID, A.BOTTOM_HEIGHT AS "bottom_height_1", D.BOTTOM_HEIGHT
"b.bottom_height_2" FROM S_PIPE_N C, S_MANY_PCP_N B 
LEFT OUTER JOIN S_PCONPT_N A ON 
A.G3E_FID=C.G3E_FID AND G3E_CID=1 L
LEFT OUTER JOIN S_PCONPT_N D ON A.G3E_FID=C.G3E_FID AND 
G3E_CID=2 WHERE C.G3E_FID=B.G3E_OWNERFID and A.BOTTOM_HEIGHT IS NOT NUL

答案 1 :(得分:1)

试试这个:

SELECT T1.G3E_FID,T1.BOTTOM_HEIGHT  AS 'bottom_height_1' , T2.BOTTOM_HEIGHT as 'bottom_height_2'
FROM
(select C.G3E_FID,A.BOTTOM_HEIGHT
FROM S_PIPE_N C, S_MANY_PCP_N B 
LEFT OUTER JOIN S_PCONPT_N A ON A.G3E_FID=B.G3E_FID  
WHERE C.G3E_FID=B.G3E_OWNERFID AND B.G3E_CID=1) T1
FULL JOIN
(SELECT C.G3E_FID,D.BOTTOM_HEIGHT 
FROM S_PIPE_N C, S_MANY_PCP_N B 
LEFT OUTER JOIN S_PCONPT_N D ON B.G3E_FID=D.G3E_FID   
WHERE C.G3E_FID=B.G3E_OWNERFID AND B.G3E_CID=2)T2
ON T1.G3E_FID = T2.G3E_FID

答案 2 :(得分:1)

  SELECT A.G3E_FID,
         MAX (CASE WHEN B.G3E_CID = 1 THEN C.BOTTOM_HEIGHT END),
         MAX (CASE WHEN B.G3E_CID = 2 THEN C.BOTTOM_HEIGHT END)
    FROM S_PIPE_N a
         INNER JOIN S_MANY_PCP_N b
            ON A.G3E_FID = B.G3E_OWNERFID
         LEFT OUTER JOIN S_PCONPT_N c
            ON B.G3E_FID = C.G3E_FID
GROUP BY A.G3E_FID;