2

我有一个名为employee 的表,其主键列ID 和一个名为supervisorID 的列,它是对引用一个人的同一个表的引用。我想将 supervisorID 显示为其引用的人名而不是 ID。

我想从表employee 中选择*,但将SupervisorID 引用为同一张表中的人名。

4

3 回答 3

9
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> 
于 2012-07-16T15:58:53.933 回答
0

就像是:

SELECT e.name as 'employee name', supervisors.name as 'supervisor name'
FROM employee e
INNER JOIN employee supervisors ON e.ID = supervisors.supervisorID
于 2012-07-16T15:46:52.033 回答
0

根据 ID 进行自加入

select e.*, s.name
from 
  employee e
  inner join employee s
    on e.supervisorid = s.id
于 2012-07-16T15:46:55.753 回答