左连接2个表,仅给出1个表的结果

时间:2018-12-14 05:23:18

标签: sql-server

我在下面有4张桌子:

Reasons_Trans:

   RTId | RId   | Label     | Lang      | 
_________________________________________________________
    1   | 1     |  No car   | English   | 
_________________________________________________________
    2   | 2     | No fuel   | English   | 

原因:

   ReId | RId   | Active| OfficeId
_________________________________________________________
    1 | 1   |  True |   1
_________________________________________________________
    2 | 2   | True  |   1

Employee_Reason:

   ERId | RId   | EmpId | 
_________________________________________________________
    1   | 1     |  1    |    
_________________________________________________________
    2   | 2     |  1    |  
_________________________________________________________
    3   | 0     |  1    |  

Employee_Reason_Trad:

   Id | ERId    | Label     | Lang
_________________________________________________________
    1 | 3       |  No in    | English
_________________________________________________________
    2 | 3       |  Out in   | English

我需要获得以下信息: 对于officeID = 1(或任何办公室),我需要获取特定员工的原因+该办公室可用的所有重新分配信息。

所以我的查询如下:

select rt.Label, ert.Label
from Reasons r
join Reasons_Trans rt
on r.RId = rt.RId and rt.Lang = 'English'
left join Employee_Reason er
on r.RId = er.RId
left join Employee_Reason_Trad ert
on er.ERId = ert.ERId and ert.Lang = 'English'
where er = 1 and r.OfficeId = 1

但是,这没有返回Employee_Reason_Trad的结果。

查询的输出应为:

  

没有汽车,没有燃料,没有进站,进站

我的查询有什么问题吗?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

不知道数据背后的逻辑,但是如果更改最后一个联接,将返回预期结果。它必须加入on er.ERId = ert.ERId而不是on er.ERId = ert.Id

select rt.Label, ert.Label
from Reasons r
join Reasons_Trans rt
on r.RId = rt.RId and rt.Lang = 'English'
left join Employee_Reason er
on r.RId = er.RId
left join Employee_Reason_Trad ert
on er.ERId = ert.Id and ert.Lang = 'English'
where er = 1 and r.OfficeId = 1

返回:

Label     Label
--------- -------
No car    No in
No fuel   Out in