1

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.

4

4 回答 4

7

如果我理解正确,您正试图field1从表 1 和field2表 2 中获取。如果是这样,您只需要加入三个表

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
于 2013-06-11T11:44:04.320 回答
0

做另一个加入。

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; 
于 2013-06-11T11:44:14.720 回答
0

您只需要加入所有三个表即可;就像是

SELECT Table1.Field1, Table2.Field2
FROM Table3
JOIN Table1 ON Table1.Id = Table3.Table1_id
JOIN Table2 ON Table2.Id = Table3.Table2_id
于 2013-06-11T11:44:15.847 回答
0

我不知道我是否正确理解了您想要实现的目标,但这应该可以让您从通过他们的键连接的两个表中获得结果

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;
于 2013-06-11T11:44:28.853 回答