在1行中连接2列

时间:2019-03-04 09:26:54

标签: sql sql-server

我有一个表,表A的结构如下:

ID  oldID  newID         
1    43     97
2    54     31

还有一个表,表B如下:

ID  partID 
129   43     
463   97
721   54
812   31

第三个表,表C如下:

partID  name
  129    A
  463    B
  721    C
  812    D

并希望查询显示以下信息:

oldPart  newPart
   A        B
   C        D

我该如何获取所需的信息以显示?

我有以下SQL:

SELECT Table C.name
FROM Table C
WHERE (Table A.oldID = Table B.partID OR Table A.newID = Table B.partID)
AND Table B.partID = Table C.partID

我明白了:

name
 A
 B
 C
 D

3 个答案:

答案 0 :(得分:2)

您需要两次连接表:

select C1.name, C2.name
from A 
join B as B1
  on a.oldID = B1.partID 
join C AS C1
  on B1.partID = C1.ID
join B as B2
  on a.newID = B2.partID 
join C AS C2
  on B2.partID = C2.ID

答案 1 :(得分:0)

加入

  select c.name as oldname,c1.name as newname from 
   (
        select   b.partID as oldpartID,b.ID as oldid
          b1.partID as newpartID,b1.ID as newid from
         tableA a join tabeB b  on a.oldID=b.partID
          join tableB b1 on a1.newID=b1.partID
    ) a join tableC c on a.oldid=c.partID
        join tableC c1 on a.newid=c1.partID

答案 2 :(得分:0)

您可以使用tableB和tableC的多个实例的连接尝试以下

select c.name as oldpart, c1.name as newpart from
(
    SELECT b.id as  bid, b1.id as b1id
    FROM TableA a inner join tableB b on a.oldID = b.partID
    join tableB b1 on a.newID=b1.partID
)A1 join TableC c on A1.bid=c.partID
join tableC c1 on A1.b1id=c1.partid