我有一个名为employee的表,其中包含一个ID为Primary Key的列和一个名为supervisorID的列,该列是对引用某个人的同一个表的引用。我想将supervisorID显示为其引用而不是ID的人名。
我想从表employee中选择*,但是将SupervisorID作为同一个表中的人名引用。
答案 0 :(得分:7)
SELECT e.ID, e.name AS Employee, s.name AS Supervisor
FROM employee e
INNER JOIN employee s
ON s.ID = e.supervisorID
ORDER BY e.ID;
以下是有关如何测试的更多颜色:
mysql> CREATE TABLE employee (ID INT NOT NULL AUTO_INCREMENT, supervisorID INT NOT NULL DEFAULT '1', name VARCHAR(48) NOT NULL, PRIMARY KEY (ID));
Query OK, 0 rows affected (0.01 sec)
mysql> INSERT INTO employee VALUES (1, 1, "The Boss"), (2,1, "Some Manager"), (3,2, "Some Worker"), (4,2, "Another Worker");
Query OK, 4 rows affected (0.00 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> SELECT e.ID, e.name AS Employee, s.name AS Supervisor
FROM employee e INNER JOIN employee s
ON s.ID = e.supervisorID ORDER BY e.ID;
+----+----------------+--------------+
| ID | Employee | Supervisor |
+----+----------------+--------------+
| 1 | The Boss | The Boss |
| 2 | Some Manager | The Boss |
| 3 | Some Worker | Some Manager |
| 4 | Another Worker | Some Manager |
+----+----------------+--------------+
4 rows in set (0.01 sec)
mysql>
答案 1 :(得分:0)
类似的东西:
SELECT e.name as 'employee name', supervisors.name as 'supervisor name'
FROM employee e
INNER JOIN employee supervisors ON e.ID = supervisors.supervisorID
答案 2 :(得分:0)
根据ID
进行自我加入select e.*, s.name
from
employee e
inner join employee s
on e.supervisorid = s.id