所以我有一张员工表:
我正在尝试创建一个显示该员工所有信息的查询,但我对Employee_Reports_To位有点困惑。我想要出现的是存储在此列中的Employee_ID的First_Name和Last_Name(例如,Joe Bloggs ID 1,向员工Joanne Blog ID 50报告)
这需要加入还是只需要一个简单的选择。当我尝试时,数据库出现链接问题..
SELECT employee.*, departments.Department_Name,
jobTitle.Job_Title,
(SELECT manager.First_Name, manager.Last_Name
FROM Employee manager
INNER JOIN employee AS employeeReportsTo
ON manager.Employee_Reports_To = manager.Employee_ID
) AS Reports_To
FROM Employee employee
LEFT JOIN Departments AS departments
ON departments.Departments_ID = employee.Departments_ID
LEFT JOIN Job_Title AS jobTitle
ON jobTitle.Job_Title_ID = employee.Job_Title_ID
ORDER BY `employee`.`Record_Active` DESC,
`employee`.`First_Name` ASC
任何帮助都将不胜感激!
答案 0 :(得分:2)
试试这个解决方案:
SELECT emp.*,
manager.First_Name,
manager.Last_Name,
departments.Department_Name,
jobTitle.Job_Title
FROM Employee emp
INNER JOIN Employee manager
ON emp.Employee_Reports_To = manager.Employee_ID
LEFT JOIN Departments AS departments
ON departments.Departments_ID = emp.Departments_ID
LEFT JOIN Job_Title AS jobTitle
ON jobTitle.Job_Title_ID = emp.Job_Title_ID
ORDER BY emp.Record_Active DESC,
emp.First_Name ASC
最好使用Join
而不是Sub Query
。
<强>编辑:强>
由于列Employee_Reports_To
可以是null
,因此最好使用LEFT JOIN
代替INNER JOIN
。像这样:
SELECT emp.*,
manager.First_Name,
manager.Last_Name,
departments.Department_Name,
jobTitle.Job_Title
FROM Employee emp
LEFT JOIN Employee manager --Changed Join here
ON emp.Employee_Reports_To = manager.Employee_ID
LEFT JOIN Departments AS departments
ON departments.Departments_ID = emp.Departments_ID
LEFT JOIN Job_Title AS jobTitle
ON jobTitle.Job_Title_ID = emp.Job_Title_ID
ORDER BY emp.Record_Active DESC,
emp.First_Name ASC
答案 1 :(得分:1)
查看您的代码,您可以使用两次Employee(别名为e1和e2)一个用于员工,一个用于相关经理
SELECT e1.*
, departments.Department_Name
, jobTitle.Job_Title
, e2.First_Name
,e2.Last_Name
FROM Employee e1
INNER JOIN Employee e2 ON e1.Employee_Reports_To = e2.Employee_ID
LEFT JOIN Departments AS departments
ON departments.Departments_ID = e1.Departments_ID
LEFT JOIN Job_Title AS jobTitle
ON jobTitle.Job_Title_ID = e1.Job_Title_ID
ORDER BY e1.`Record_Active` DESC,
e1.`First_Name` ASC