从连接中具有多个ID的一个表中获取名称

时间:2014-04-03 05:29:44

标签: mysql sql join subquery inner-join

员工

ID    Name   
1     John
2     Williams

预约

ID  DoctorName   Employee_id  Team lead
1    willson          1            2

SQL

SELECT E.*,A.* FROM Employee as E,Appointment as A WHERE A.Employee_id = E.ID

如果我想要获取团队负责人名称我们如何做到这一点,这是我的加入?

5 个答案:

答案 0 :(得分:0)

试试这个:

SELECT A.ID,A.DoctorName,E.Name as Employee,E1.Name as TeamLead
FROM Appointment A INNER JOIN
Employee E ON E.ID=A.Employee_id INNER JOIN
Employee E1 ON E1.ID=A.TeamLead

结果将是:

ID  DoctorName  Employee_id   TeamLead
---------------------------------------
1   willson     John          Williams

请参阅SQL Fiddle中的结果。

修改

要包含更多表,您需要使用不同的别名加入Employee表:

SELECT A.ID,A.DoctorName,E.Name as Employee,E1.Name as TeamLead,E2.Name as AttendedBy, Att.Attended
FROM Appointment A INNER JOIN
tblAttended Att ON Att.Id=A.Id INNER JOIN
Employee E ON E.ID=A.Employee_id INNER JOIN
Employee E1 ON E1.ID=A.TeamLead INNER JOIN
Employee E2 ON E2.ID=Att.employee_id

示例结果:

ID  DoctorName  Employee_id   TeamLead    AttendedBy     Attended
-----------------------------------------------------------------
1   willson     John          Williams    John           Y

答案 1 :(得分:0)

试试这个

SELECT E.name
FROM Employee E
JOIN Appointment A 
ON A.Employee_id = E.ID
WHERE [some condition here]

答案 2 :(得分:0)

试试这个:

SELECT A.ID,A.DoctorName,E.Name,E1.Name 
FROM Employee E
INNER JOIN Appointment A
ON A.Employee_id = A.ID
WHERE E1.ID=A.Teamlead

答案 3 :(得分:0)

您还没有使用过加入。你需要在这里使用join。您的TeamLead必须与Employee id相同。基于此,您必须选择Employee名称,并将其别名为TeamLeadName。

SELECT A.ID, A.DoctorName, A.Employee_id, E.Name as TeamLeadName
FROM Appointment A
JOIN Employee E
ON A.TeamLead = E.ID

答案 4 :(得分:0)

如果团队在预约表中领导姓名,请使用以下QUERY:

SELECT E.Name AS 'Employee Name',A.DoctorName AS 'Doctor', A.TeamLeadName AS 'Team Lead' FROM Employee AS E,Appointment AS A WHERE A.Employee_id = E.ID;

如果团队领导NAME IN的表格不同,那么TeamLead会在QUERY下方使用:

SELECT E.Name AS 'Employee Name',A.DoctorName AS 'Doctor', T.TeamLeadName AS 'Team Lead' FROM Employee AS E,Appointment AS A, TeamLead AS T WHERE A.Employee_id = E.ID AND A.TeamLead=T.TeamLead_ID;

如果Williams是teamlead(在您的问题中未提及),请使用以下查询:

SELECT E.Name AS 'Employee Name',A.DoctorName AS 'Doctor', T.Name AS 'Team Lead' FROM Employee AS E,Appointment AS A, Employee AS T WHERE A.Employee_id = E.ID AND A.TeamLead=T.ID;