Nicola Ambrosetti
Nicola Ambrosetti

Reputation: 2504

Selecting a mapping table with fields from two other tables

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:

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.

Upvotes: 1

Views: 6799

Answers (4)

gzaxx
gzaxx

Reputation: 17600

I do not know if I understood correctly what you want to achieve but this should get you results from both tables joined by thier keys

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

Upvotes: 0

nurdglaw
nurdglaw

Reputation: 2127

You just need to join all three tables; something like

SELECT Table1.Field1, Table2.Field2
FROM Table3
JOIN Table1 ON Table1.Id = Table3.Table1_id
JOIN Table2 ON Table2.Id = Table3.Table2_id

Upvotes: 0

Edwin Stoteler
Edwin Stoteler

Reputation: 1228

Do another join.

SELECT Table1.field1, Table2.field
FROM Table1
INNER JOIN Table3
ON Table1.id = Table3.Table1_id
INNER JOIN Table 2 
ON Table2.id = table3.table2_id; 

Upvotes: 0

Fabio
Fabio

Reputation: 23510

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

Upvotes: 8

Related Questions