我有两张表格如下
表A
ID ExPID ExWIPID Type
1 15 30 P1
2 16 0 P2
表B
EXPID Label Value
15 Label A Label A Val
30 Label B Label B Val
16 Label C Label C Val
从上表中,表A的PID和WIPID都来自表B ID 我想编写一个查询结果如下:
ID PID WIPID Type Label Label
1 15 30 P1 Label A Label B
2 16 0 P2 Label C NULL
请帮助
答案 0 :(得分:1)
你可以在wipid上使用左连接来获得带有标签的3行2和带有
的1行select a.ID, a.ExPID, a.ExWIPID, a.Type, b.Label label_x_pid, c.label label_x_wiPDi
from tableA a
left join tableB b on a.exID = b.EXPID
left join tableB c on a.ExWIPID = c.EXPid
但如果只需要匹配的两个,则应使用内连接
select a.ID, a.ExPID, a.ExWIPID, a.Type, b.Label label_x_pid, c.label label_x_wiPDi
from tableA a
inner join tableB b on a.exID = b.EXPID
inner join tableB c on a.ExWIPDI = c.EXPid
根据您的评论,您应该使用
select a.ID, a.ExPID, a.ExWIPID, a.Type, b.Label label_x_pid, c.label label_x_wiPDi
from tableA a
left join tableB b on a.exID = b.EXPID
left join tableB c on a.ExWIPID = c.EXPID
where a.ID =1