假设您的表是:
mysql> SELECT * FROM Employee;
+-----+------+-------------+------+
| SSN | Name | Designation | MSSN |
+-----+------+-------------+------+
| 1 | A | OWNER | 1 |
| 10 | G | WORKER | 5 |
| 11 | D | WORKER | 5 |
| 12 | E | WORKER | 5 |
| 2 | B | BOSS | 1 |
| 3 | F | BOSS | 1 |
| 4 | C | BOSS | 2 |
| 5 | H | BOSS | 2 |
| 6 | L | WORKER | 2 |
| 7 | I | BOSS | 2 |
| 8 | K | WORKER | 3 |
| 9 | J | WORKER | 7 |
+-----+------+-------------+------+
12 rows in set (0.00 sec)
查询是:
SELECT SUPERVISOR.name AS SuperVisor,
GROUP_CONCAT(SUPERVISEE.name ORDER BY SUPERVISEE.name ) AS SuperVisee,
COUNT(*)
FROM Employee AS SUPERVISOR
INNER JOIN Employee SUPERVISEE ON SUPERVISOR.SSN = SUPERVISEE.MSSN
GROUP BY SuperVisor;
查询将产生如下结果:
+------------+------------+----------+
| SuperVisor | SuperVisee | COUNT(*) |
+------------+------------+----------+
| A | A,B,F | 3 |
| B | C,H,I,L | 4 |
| F | K | 1 |
| H | D,E,G | 3 |
| I | J | 1 |
+------------+------------+----------+
5 rows in set (0.00 sec)
[答案]:这对于一个级别(立即监督)要查找所有可能级别的所有监督,您必须使用 while 循环(使用存储过程)。
尽管可以检索每个级别的员工,然后获取他们的 UNION,但通常我们不能在不使用循环机制的情况下指定诸如“检索所有级别的员工的监督者”之类的查询。"
参考:在这张幻灯片中阅读幻灯片编号 23。这本书是“第四版数据库系统基础”,在“关系代数和关系微积分”一章中有一个主题“递归闭包运算”。
为创建表添加查询,可能对您有帮助:
mysql> CREATE TABLE IF NOT EXISTS `Employee` (
-> `SSN` varchar(64) NOT NULL,
-> `Name` varchar(64) DEFAULT NULL,
-> `Designation` varchar(128) NOT NULL,
-> `MSSN` varchar(64) NOT NULL,
-> PRIMARY KEY (`SSN`),
-> CONSTRAINT `FK_Manager_Employee` FOREIGN KEY (`MSSN`) REFERENCES Employee(SSN)
-> ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Query OK, 0 rows affected (0.17 sec)
您可以检查表,如:
mysql> DESCRIBE Employee;
+-------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+-------+
| SSN | varchar(64) | NO | PRI | NULL | |
| Name | varchar(64) | YES | | NULL | |
| Designation | varchar(128) | NO | | NULL | |
| MSSN | varchar(64) | NO | MUL | NULL | |
+-------------+--------------+------+-----+---------+-------+
4 rows in set (0.00 sec)