我有两个相关的表:具有3列的合同:ContractsID,AreaManager和AreaLeader。然后我有两列Employees表:EmployeesID,EmployeeName。 EmployeeID既是AreaManager的外键,也是AreaLeader的外键。我正在尝试创建一个SELECT查询来回显ContractID,区域经理的名字和区域负责人的名字。
这就是我所拥有的;
$query = "SELECT Contracts.ContractsID, Contracts.AreaLeader, Contracts.AreaManager, Employees.EmployeeName FROM Contracts
INNER JOIN Employees ON Employees.EmployeeID = Contracts.AreaManager
INNER JOIN Employees ON Employees.EmployeeID = Contracts.AreaLeader
但是,查询不起作用。我相信我应该使用表别名,但我有点挣扎。
我尝试了这个,但它不起作用:
$query = "SELECT c.ContractsID, m.Employees.EmployeeName as ManagerName, l.Employees.EmployeeName as LeaderName
FROM c.Contracts
JOIN Employees m ON m.EmployeeID = c.AreaManager
JOIN Employees l ON l.EmployeeID = c.AreaLeader
非常感谢任何帮助!
答案 0 :(得分:1)
您在第二个查询中使用了正确的方法,但是它中存在语法错误。您的查询将如下所示:
$query = "SELECT c.ContractsID, m.EmployeeName as ManagerName, l.EmployeeName as LeaderName
FROM Contracts c
JOIN Employees m ON m.EmployeeID = c.AreaManager
JOIN Employees l ON l.EmployeeID = c.AreaLeader"
答案 1 :(得分:1)
原始查询不起作用的原因是因为您与Employees
一起加入了两次,并且您需要对它们进行别名以进行区分。
$query = "SELECT Contracts.ContractsID, Contracts.AreaLeader, Contracts.AreaManager, Employees.EmployeeName FROM Contracts
INNER JOIN Employees Employee1 ON Employee1.EmployeeID = Contracts.AreaManager
INNER JOIN Employees Employee2 ON Employee2.EmployeeID = Contracts.AreaLeader
除非你想这样做,否则你不需要别名Contracts
。
您的第二个查询失败,因为您没有正确别名Contracts
。您应该放置Contracts c
而不是c.Contracts
。