[英]Query to fetch row values (first_name & last_name) using foreign key
New to SQL and MySQL. SQL 和 MySQL 的新手。
In the below table, I've a table of employees where emp_id is employee's ID & super_id is supervisor's employee ID.在下表中,我有一张员工表,其中 emp_id 是员工的 ID,super_id 是主管的员工 ID。 Here super_id is assigned as foreign key of employee table itself.这里 super_id 被分配为员工表本身的外键。
Now I need to fetch a table with three columns: first_name (supervisor), last_name (supervisor) and Count of employees who are supervised by this employee.现在我需要获取一个包含三列的表:first_name(主管)、last_name(主管)和受该员工监督的员工人数。
For Example:例如:
David Wallace 3
Michael Scott 3
Josh Porter 2
Thanks in advance提前致谢
This is a self-join:这是一个自连接:
select tsuper.first_name, tsuper.last_name, count(*)
from t join
t tsuper
on t.super_id = tsuper.emp_id
group by tsuper.first_name, tsuper.last_name;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.