简体   繁体   中英

join multiple times in SQL

These are the 2 tables. Tech_data:

Id Tech Agent1_id Agent2_ID
1  JAVA   1           2   
2  SQL    3           4

Agent_table

Id Name
1  Mike
2  John
3  Jim
4  Baron

I need to write a query to bring the below output

TECH_ID   Tech  Agent1_Name Agent2_Name
1         Java    Mike       John
2         SQL     Jim        Baron

I wrote LEFT OUTER JOIN ON tech_id=agent1_id, but i do not know how to join 2 ids in ON condition.

To prevent having to do multiple joins to the same table, you can unpivot, join and then pivot (then if you had 50 ID columns you would still only need to perform one join):

SQL Fiddle

Oracle 11g R2 Schema Setup :

CREATE TABLE Tech_data (Id, Tech, Agent1_id, Agent2_ID ) AS
SELECT 1,  'JAVA', 1, 2 FROM DUAL UNION ALL
SELECT 2,  'SQL',  3, 4 FROM DUAL;

CREATE TABLE Agent_table ( Id, Name ) AS
SELECT 1,  'Mike' FROM DUAL UNION ALL
SELECT 2,  'John' FROM DUAL UNION ALL
SELECT 3,  'Jim' FROM DUAL UNION ALL
SELECT 4,  'Baron' FROM DUAL;

Query 1 :

SELECT *
FROM   (
  SELECT t.id,
         t.tech,
         t.num,
         a.name
  FROM   (
      SELECT *
      FROM   tech_data
      UNPIVOT ( Agent_ID FOR num IN ( Agent1_id AS 1, Agent2_id AS 2 ) )
    ) t
    INNER JOIN Agent_table a
    ON ( t.agent_id = a.id )
)
PIVOT ( MAX( name ) FOR num IN ( 1 AS Agent1_Name, 2 AS Agent2_Name ) )

Results :

| ID | TECH | AGENT1_NAME | AGENT2_NAME |
|----|------|-------------|-------------|
|  1 | JAVA |        Mike |        John |
|  2 |  SQL |         Jim |       Baron |

You can add a second left outer join just like the one you have used, on the same table by giving them different aliases as follows.

select t.Id tech_id, t.tech, a1.name, a2.name
from tech_data t
left outer join agent_table a1 on a1.Id = t.agent1_id
left outer join agent_table a2 on a2.Id = t.agent2_Id;

Check the fiddle below: http://sqlfiddle.com/#!4/73f02b/1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM