Sql – Selecting a mapping table with fields from two other tables

inner-joinsql

I have a mapping table referring to ids from two different tables. I would like to select the mapping table with each id being replaced by another field in the respective table.

To be a little more explicit: there are three tables with two columns each:

  • Table1 has a id (the primary key) and field1
  • Table2 has a id (the primary key) and field2
  • Table3 (the mapping table) has fields Table1_id (which takes values in Table1.id) and Table2_id (which takes values in Table2.id)

What I want is to get the content of Table3 with Table1.field1 and Table2.field2 as columns.

I know how to replace one of the columns in the mapping table with another column of one of the other tables, by using a inner join:

SELECT Table1.field1, Table3.Table2_id
FROM Table1
INNER JOIN Table3
ON Table1.id=Table3.Table1_id; 

however I don't know how to do basically the same thing with both columns.

Best Answer

If i understood correctly you are trying to get field1 from Table1 and field2 from table 2. If so you just need to join the three tables

SELECT a.field1, c.field2
FROM Table1 a
INNER JOIN Table3 b
ON a.id=b.Table1_id
INNER JOIN Table2 c
ON b.Table2_id = c.id