如何从一个源表连接到3个不同的字段?

时间:2016-03-09 08:06:26

标签: oracle

我有一个包含主要记录ID和子ID的表。 我有一个Oracle表“记录”,如下所示:

'Records' TABLE STRUCTURE:

| main_id  | sub_id1 | sub_id2 | sub_id3 | 
------------------------------------------
| 1        | 100     | 202     | 350     |
| 2        | 101     | 203     | 375     |
| 3        | 102     | 204     | 400     |
| 4        | 103     | 205     | 2000    |

现在,我想从另一个表中获取sub_ids的名称,这些表中包含一列中所有sub_ids的名称。 我有一个Oracle表“名称”,如下所示:

'Name' TABLE STRUCTURE:

| sub_id    | id_name | 
-----------------------
| 100       | Gamma   |
| 202       | Phi     |
| 350       | Betta   | 

我基本上需要加入不同的sub_ids并在一个表中显示每个名称。

'Result' TABLE STRUCTURE:

| main_id  | sub_id1 | id_name1| sub_id2 | id_name2| sub_id3 | id_name3 |
------------------------------------------------------------------------
| 1        | 100     | Gamma   | 202     | Phi     | 350     | Betta    |      
| 2        | ...     | ...     | ...     |

我已尝试使用不同联接的以下查询的多个版本,并且无法获取任何位置。谢谢你的帮助!

SELECT 
records.main-id,
records.sub_id1, 
name.id_name as id_name1, 
records.sub_id2, 
name.id_name as id_name2,
records.sub_id3, 
name.id_name as id_name3,
FROM  records, Name
WHERE 
records.sub_id1 = name.id_name
OR records.sub_id2 = name.id_name
OR records.sub_id3 = name.id_name

3 个答案:

答案 0 :(得分:0)

您可以使用一系列3个内连接完成此操作,所有这些连接都在同一个Name表中:

SELECT r.main_id, r.sub_id1, n1.id_name AS id_name1,
                  r.sub_id2, n2.id_name AS id_name2,
                  r.sub_id3, n3.id_name AS id_name3
FROM records r
INNER JOIN name n1
    ON r.sub_id1 = n1.sub_id
INNER JOIN name n2
    ON r.sub_id2 = n2.sub_id
INNER JOIN name n3
    ON r.sub_id3 = n3.sub_id

答案 1 :(得分:0)

你可以加入name表三次,每列一次你想得到:

SELECT r.main-id,
       r.sub_id1, 
       n1.id_name as id_name1, 
       r.sub_id2, 
       n2.id_name as id_name2,
       r.sub_id3, 
       n3.id_name as id_name3,
FROM   records r
JOIN   name n1 ON r.sub_id1 = n1.sub_id
JOIN   name n2 ON r.sub_id2 = n2.sub_id
JOIN   name n3 ON r.sub_id3 = n3.sub_id

答案 2 :(得分:0)

SELECT t1.main_id , t1.sub_id1  , t2.id_name , t2.sub_id, t1.sub_id2 , t1.sub_id3, t3.id_name,t4.id_name
FROM records t1 INNER JOIN NAME t2 ON t1.sub_id1=t2.sub_id INNER JOIN NAME t3
ON t1.sub_id3=t3.sub_id INNER JOIN NAME t4 ON t1.sub_id2=t4.sub_id;