我有三张桌子,如下图所示。
注意: projectheader表的Lead列存储员工ID。
我想要的是能够检索表格中的那个我的目标(Lead,显示该员工的主要名称)
我能够使用下面的查询来做到这一点。
SELECT DISTINCT
projectdetails.ProjectDetailsID,
projectheader.ProjectID,
projectheader.ProjectName,
projectheader.Lead,
projectheader.StartDate,
projectheader.EndDate,
projectheader.Status,
projectheader.Remarks,
projectdetails.EmployeeID,
employee.Firstname,
employee.Lastname,
Lead.Leadname
FROM
projectheader,
projectdetails,
employee,
( SELECT
projectheader.ProjectID AS projid,
CONCAT(employee.Firstname,' ',employee.Lastname) AS Leadname
FROM employee, projectheader, projectdetails
WHERE projectheader.ProjectID = projectdetails.ProjectID
AND projectheader.Lead = employee.EmployeeID
) AS Lead
WHERE projectheader.ProjectID = projectdetails.ProjectID
AND projectdetails.EmployeeID = employee.EmployeeID
AND projectheader.ProjectID = Lead.projid
AND projectdetails.ProjectID = Lead.projid
得到了这个结果:
我使用的查询很长,也许编写得不好,我想知道如何通过使用join或子查询使用更好的sql查询来实现相同结果的不同方式。 (我在projectdetails.ProjectDetailsID的开头添加了一个DISTINCT,因为没有它会重复一些行)。我正在寻找比我目前正在使用的查询更好的查询。
答案 0 :(得分:2)
尝试这样的事情(没有测试过,你可以尝试一下):
SELECT
projectdetails.ProjectDetailsID,
projectheader.ProjectID,
projectheader.ProjectName,
projectheader.Lead,
projectheader.StartDate,
projectheader.EndDate,
projectheader.Status,
projectheader.Remarks,
projectdetails.EmployeeID,
employee.Firstname,
employee.Lastname,
CONCAT(Lead.Firstname,' ',Lead.Lastname) AS Leadname
FROM
projectheader,
projectdetails,
employee,
employee as Lead
WHERE projectheader.ProjectID = projectdetails.ProjectID
AND projectdetails.EmployeeID = employee.EmployeeID
AND projectheader.Lead = Lead.EmployeeID
答案 1 :(得分:2)
尝试此查询我希望它可以为您工作
SELECT pd.ProjectDetailsID,ph.*,e.* FROM
`projectdetail` pd
INNER JOIN projectheader ph ON ph.ProjectID = pd.ProjectID
INNER JOIN employee e ON e.EmployeeID = pd.EmployeeID