问题
Employee
ID Name
1 John
2 Williams
Appointment
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
This is my join if i want to fetch Team lead name how we can do that?
回答1:
Try this one
SELECT E.name
FROM Employee E
JOIN Appointment A
ON A.Employee_id = E.ID
WHERE [some condition here]
回答2:
IF Team Lead NAME IN Appointment TABLE THEN USE below 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;
IF Team lead NAME IN differnt TABLE LIKE TeamLead THEN USE below 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;
If Williams is teamlead (which is not mention in your question) then use below query:
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;
回答3:
try this:
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
回答4:
You have not used join. You need to use join here. Your TeamLead must be the same as Employee id. Based on that, you have to select the Employee name, and alias it as TeamLeadName.
SELECT A.ID, A.DoctorName, A.Employee_id, E.Name as TeamLeadName
FROM Appointment A
JOIN Employee E
ON A.TeamLead = E.ID
回答5:
Try this:
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
The result will be:
ID DoctorName Employee_id TeamLead
---------------------------------------
1 willson John Williams
See result in SQL Fiddle.
EDIT:
For including more tables, you need to join Employee
table with different alias name:
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
Sample Result:
ID DoctorName Employee_id TeamLead AttendedBy Attended
-----------------------------------------------------------------
1 willson John Williams John Y
来源:https://stackoverflow.com/questions/22828603/fetching-names-from-one-table-with-multiple-ids-in-join