[英]Getting a value using only the primary key and foreign key
I have already tried several queries
and joins
and I can't solve this question. 我已经尝试了几个
queries
和joins
,但无法解决此问题。
I have 2 tables 我有2张桌子
Employee
--------
ID(PK)
Firstname
Lastname
ContactNumber
Position
TeamleaderID(FK) //*which is only applicable if the position isn't a team leader*//
Team Leader
----------
ID(PK)
employeeID(FK)
Employee
table consists of 2 data, the first one is. Employee
表包含2个数据,第一个是。
ID(PK) - 1
Firstname - Mikael
Lastname - Roque
ContactNumber - 0010101
Position - TeamLeader
TeamleaderID(FK) - Null
2nd one is 第二个是
ID(PK) - 2
Firstname - Rinnie
Lastname - Hoshino
ContactNumber - 0010101
Position - Engineer
TeamleaderID(FK) - 1
3rd one is for the teamleader
table 第三个是
teamleader
表
ID(PK) - 1
employeeID(FK) - 1
I've tried this query 我已经试过这个查询
SELECT employee.*
FROM employee
JOIN teamleader
ON employee.teamleader_id=teamleader.teamleader_id
Where employee.firstname='Rinnie';
but the result is the teamleader
id was only shown. 但结果是仅显示了
teamleader
ID。 Is it possible to select all the employee
data including the name of the teamleader
? 是否可以选择所有
employee
数据,包括teamleader
的姓名?
You need another join for getting result: 您需要另一个联接才能获得结果:
SELECT employee.*,leader.*
FROM employee
LEFT JOIN teamleader ON employee.teamleader_id=teamleader.teamleader_id
LEFT JOIN employee as leader ON teamleader.employeeID = leader.ID
Where employee.firstname='Rinnie';
I added left join for employeee without teamleader. 我为没有团队领导者的员工添加了左加入。
Please try the query as shown. 请尝试如图所示的查询。 The issue with your posted query is that you are not selecting the team leader's name, only the original employee.
您发布的查询的问题在于您没有选择团队负责人的姓名,而只选择了原始员工。 To get the team leader's name as well, you will have to join to another instance of the employee table (employee_1) and link to the employeeId field in table teamleader.
要获得团队负责人的姓名,您还必须加入到employee表的另一个实例(employee_1),并链接到表teamleader中的employeeId字段。
SELECT e.*, m.FirstName as TeamLead
FROM employee e
join teamlead on e.TeamleaderId = teamlead.ID
join employee m on teamlead.employeeID = m.ID
WHERE e.FirstName = "Rinnie";
Cheers, 干杯,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.