将所有多列连接到另一个 table 的同一列

Join all multiple columns to the same column of another table

假设我有两个表:

Table "Combinations"

first  second  result
1      1       0
1      2       1
1      3       0
2      3       2

Table "Names"

ID  Name
1   Item1
2   Item2
3   Item3

我如何将它们连接到这样的输出中?基本上只是为了 "looking up" 个 ID?

firstItem  secondItem  resultingItem
Item1      Item1       -
Item1      Item2       Item1
Item1      Item3       -
Item2      Item3       Item2

"Combinations" table 中的 trhee 列保存 "Names" table 的 ID 值,所以基本上你有三个相同字段的前键table.

为了也列出没有结果的组合,我们需要使用左连接或右连接,以保留与结果列不匹配的组合记录。在下面的查询中,我使用左连接,因为组合 table 位于条件的左侧。

这可以这样完成:

select n1.Name, n2.Name, nr.Name
from
Combinations c left join Names n1 on c.first = n1.ID
left join Names n2 on c.second = n2.ID
left join Names nr on c.result = nr.ID;