我有一个名为 employee 的表,其中有一个主键列 ID 和一个名为 supervisorID 的列,它是对引用一个人的同一个表的引用。我想将 supervisorID 显示为其引用的人名而不是 ID。
我想从表 employee 中选择 * 但引用 SupervisorID 作为同一个表中的人名。
最佳答案
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>
关于sql - 显示引用名称而不是同一表中的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11507783/