Sql 将WHERE子句与JOIN一起使用
当有多个联接且where子句只需应用于其中一个联接(最后一个联接)时,如何使用where子句。我使用了下面的where子句,它只适用于第二次连接,但我的做法似乎不正确,有什么建议吗Sql 将WHERE子句与JOIN一起使用,sql,sql-server,tsql,Sql,Sql Server,Tsql,当有多个联接且where子句只需应用于其中一个联接(最后一个联接)时,如何使用where子句。我使用了下面的where子句,它只适用于第二次连接,但我的做法似乎不正确,有什么建议吗 SELECT A.Name , B.Address , B.City , C.Position , C.Salary , D.WorkTime as Time From Employee as A Left Join EmployeeAddr
SELECT A.Name
, B.Address
, B.City
, C.Position
, C.Salary
, D.WorkTime as Time
From Employee as A
Left Join EmployeeAddressInfo as B
on A.EID = B.AddId
Left Join EmployeeRoleInfo as C
on A.EID = C.RoleID
Left Join EmployeeTime as D
on A.EID = D.TimeID
where Position='Engineer'
where
子句将外部联接转换为内部联接。您需要将其移动到相应的on
子句。例如,如果位置
位于员工时间
:
From Employee A Left Join
EmployeeAddressInfo B
on A.EID = B.AddId Left Join
EmployeeRoleInfo C
on A.EID = C.RoleID Left Join
EmployeeTime D
on A.EID = D.TimeID and D.Position = 'Engineer'
我还强烈建议您使用表别名的缩写,而不是无意义的字符。例如:
From Employee e Left Join
EmployeeAddressInfo eai
on e.EID = eai.AddId Left Join
EmployeeRoleInfo er
on e.EID = er.RoleID Left Join
EmployeeTime et
on e.EID = et.TimeID and et.Position = 'Engineer'
您希望使用什么WHERE子句?“Position”列也属于该表中的EmployeeTime表我只想为值“Engineer”选择工时编辑您的问题并提供示例数据和所需结果。当我在表C的查询值中添加和et.Position='Engineer'时,为空…如果没有和et.Position='Engineer',我可以从表中获得所有值C@Jr.Developer . . . 如果这样做有效,你是否有理由不接受答案,并在8小时后选择另一个似乎不正确的帖子(该列取自错误的表格)?作为OP,你可以接受任何你喜欢的答案,但这似乎很奇怪。根据OP的评论,这个答案是不正确的。很奇怪,OP接受了它。
SELECT A.Name
, B.Address
, B.City
, C.Position
, C.Salary
, D.WorkTime as Time
From Employee as A
Left Join EmployeeAddressInfo as B
on A.EID = B.AddId
Left Join EmployeeRoleInfo as C
on A.EID = C.RoleID and C.Position='Engineer'
Left Join EmployeeTime as D
on A.EID = D.TimeID