我有一个问题,我没有得到答案。请仔细看看
员工数据存储在Employee表中,其中包含以下列:
EmployeeId(Varchar) 名称(Varchar) ManagerId(Varchar) ManagerId指的是员工向其报告的经理的员工ID。
假设所有员工姓名都是唯一的,请根据管理名称编写查询以获取所有直接子坐标的名称
答案 0 :(得分:1)
SELECT Name
FROM Employee
WHERE ManagerId = (SELECT manager.EmployeeId
FROM Employee AS manager
WHERE manager.Name = '.....');
或使用自我加入:
SELECT empl.Name
FROM Employee mana
JOIN Employee empl
ON mana.EmployeeId = empl.ManagerId
WHERE mana.Name = '.....';
答案 1 :(得分:0)
表格EMP中的内容
+-------+--------+-----------+------+-------------+------+------+--------+
| EMPNO | ENAME | JOB | MGR | HIREDATE | SAL | COMM | DEPTNO |
+-------+--------+-----------+------+-------------+------+------+--------+
| 7839 | KING | PRESIDENT | | 17/Nov/1981 | 5000 | | 10 |
| 7698 | BLAKE | MANAGER | 7839 | 01/May/1981 | 2850 | | 30 |
| 7782 | CLARK | MANAGER | 7839 | 09/Jun/1981 | 2450 | | 10 |
| 7566 | JONES | MANAGER | 7839 | 02/Apr/1981 | 2975 | | 20 |
| 7788 | SCOTT | ANALYST | 7566 | 09/Dec/1982 | 3000 | | 20 |
| 7902 | FORD | ANALYST | 7566 | 03/Dec/1981 | 3000 | | 20 |
| 7369 | SMITH | CLERK | 7902 | 17/Dec/1980 | 800 | | 20 |
| 7499 | ALLEN | SALESMAN | 7698 | 20/Feb/1981 | 1600 | 300 | 30 |
| 7521 | WARD | SALESMAN | 7698 | 22/Feb/1981 | 1250 | 500 | 30 |
| 7654 | MARTIN | SALESMAN | 7698 | 28/Sep/1981 | 1250 | 1400 | 30 |
| 7844 | TURNER | SALESMAN | 7698 | 08/Sep/1981 | 1500 | 0 | 30 |
| 7876 | ADAMS | CLERK | 7788 | 12/Jan/1983 | 1100 | | 20 |
| 7900 | JAMES | CLERK | 7698 | 03/Dec/1981 | 950 | | 30 |
| 7934 | MILLER | CLERK | 7782 | 23/Jan/1982 | 1300 | | 10 |
+-------+--------+-----------+------+-------------+------+------+--------+
<强>查询强>
SELECT e1.empno EmployeeId, e1.ename EmployeeName,
e1.mgr ManagerId, e2.ename AS ManagerName
FROM emp e1, emp e2
where e1.mgr = e2.empno
and e2.ename='JONES';
自我加入
select *
from emp employee
join emp manager
on manager.empno=employee.mgr
where manager.ename='JONES'
<强>结果强>
+------------+--------------+-----------+-------------+
| EMPLOYEEID | EMPLOYEENAME | MANAGERID | MANAGERNAME |
+------------+--------------+-----------+-------------+
| 7902 | FORD | 7566 | JONES |
| 7788 | SCOTT | 7566 | JONES |
+------------+--------------+-----------+-------------+
P.S - 我在Oracle DB上测试而不是MySQL。但是代码仍适用于MySQL