多个加倍JOIN到同一张表

时间:2019-03-03 21:13:05

标签: sql informix

示例1(工作正常,选择 assignedagent ):

select cr.callid, cr.callstart, cr.callend, cr.waittime, cr.origin,
cr.origdestination, cr.waitresolution, cr.contacttype, cr.termtype,
u.userlastname as assignedagentname,
"" as answeringagentname from callrecord cr
left join (agentrecord ar left join users u on ar.agentkey=u.userkey)
on (cr.callid=ar.callid and cr.assignedagent=ar.sequencenumber);

示例2(工作正常,选择 answeringagent ):

select cr.callid, cr.callstart, cr.callend, cr.waittime, cr.origin,
cr.origdestination, cr.waitresolution, cr.contacttype, cr.termtype,
"" as assignedagentname,
u.userlastname as answeringagentname from callrecord cr
left join (agentrecord ar left join users u on ar.agentkey=u.userkey)
on (cr.callid=ar.callid and cr.answeringagent=ar.sequencenumber);

示例3(产生错误,请同时选择两者):

select cr.callid, cr.callstart, cr.callend, cr.waittime, cr.origin,
cr.origdestination, cr.waitresolution, cr.contacttype, cr.termtype,
u1.userlastname as assignedagentname,
u2.userlastname as answeringagentname from callrecord cr
left join (agentrecord ar left join users u1 on ar.agentkey=u1.userkey)
on (cr.callid=ar.callid and cr.assignedagent=ar.sequencenumber)
left join (agentrecord ar left join users u2 on ar.agentkey=u2.userkey)
on (cr.callid=ar.callid and cr.answeringagent=ar.sequencenumber);

示例1和2可以正常工作并返回真实结果。在示例3中,我遵循了有关在此论坛中找到的多个联接的别名的建议,但是没有成功。我通过ODBC驱动程序使用Informix DB。

1 个答案:

答案 0 :(得分:1)

尝试删除括号并确保所有别名都是唯一的:

select cr.callid, cr.callstart, cr.callend, cr.waittime, cr.origin,
       cr.origdestination, cr.waitresolution, cr.contacttype, cr.termtype,
       u1.userlastname as assignedagentname,
       u2.userlastname as answeringagentname
from callrecord cr left join
     agentrecord ar1
     on cr.callid = ar1.callid and
        cr.assignedagent = ar1.sequencenumber left join
     users u1
     on ar.agentkey = u1.userkey left join
     agentrecord ar2 
     on cr.callid = ar2.callid and 
        cr.answeringagent = ar2.sequencenumber left join
     users u2 on ar2.agentkey = u2.userkey