在行的多列上执行SQL Join

时间:2018-09-19 07:49:41

标签: sql join

我有下表IDDetails:

ID1 ID2 ID3
1   2   3
1   5   7 and so on

我想用名称表中的名称链接该行的每个ID:

ID Name
1  A
2  B
3  C
4  D
5  E
7  G

输出应该有6列,如:

ID1 Name1 ID2 Name2 ID3 Name3
1   A     2   B     3   C
1   A     5   E     7   G

该操作应具有最少的联接且成本有限。

1 个答案:

答案 0 :(得分:4)

此查询将为您提供所需的结果。请注意,您必须JOINNames 3次才能获得每一行的三个不同名称。

SELECT i.ID1, n1.Name AS Name1,
       i.ID2, n2.Name AS Name2,
       i.ID3, n3.Name AS Name3
FROM IDDetails i
JOIN Names n1 on n1.ID = i.ID1
JOIN Names n2 on n2.ID = i.ID2
JOIN Names n3 on n3.ID = i.ID3

输出:

ID1     Name1   ID2     Name2   ID3     Name3
1       A       2       B       3       C
1       A       5       E       7       G

更新

这是一个没有JOIN的查询,按照原始帖子之后的编辑要求:

SELECT i.ID1, (SELECT Name FROM Names n WHERE n.ID = i.ID1) AS Name1,
       i.ID2, (SELECT Name FROM Names n WHERE n.ID = i.ID2) AS Name2,
       i.ID3, (SELECT Name FROM Names n WHERE n.ID = i.ID3) AS Name3
FROM IDDetails i

输出:

ID1     Name1   ID2     Name2   ID3     Name3
1       A       2       B       3       C
1       A       5       E       7       G

SQLFiddle Demo of both queries