8

我有三个表,如下图所示。

注意: projectheader 表的 Lead 列存储员工 ID。

在此处输入图像描述

我想要的是能够检索到我的目标表中的内容(领导,显示该员工的领导姓名)

我可以使用下面的查询来做到这一点。

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

并得到了这个结果: 在此处输入图像描述

我使用的查询很长,可能写得不好,我想知道如何使用更好的 sql 查询通过连接或子查询来获得相同的结果。(我在 projectdetails.ProjectDetailsID 的开头添加了一个 DISTINCT,因为没有它,有些行会重复)。我正在寻找比我目前使用的更好的查询。

4

2 回答 2

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
于 2012-06-24T08:16:51.343 回答
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 
于 2012-06-24T08:40:18.447 回答