标签:sql 组织结构
如何设计一张表来存储一个公司的所有员工信息,员工信息时有上下级关系的,如何可以快速查到一个员工所管理的所有人员?
Tree
CEO 1
|--Manage1 11
|-------Leader1 111
| |-------employee1 1111
| |-------employee2 1112
|
|-------Leader2 112
|-------employee3 1121
|-------employee4 1122
...
table_employees
id name parent_id employee_id
1 CEO NULL 1
2 Manager1 1 11
3 Leader1 2 111
4 employee1 3 1111
5 employee2 3 1112
6 Leader2 2 112
7 employee3 6 1121
8 employee4 6 1122
.....
SELECT * FROM table_employees WHERE parent_id = 2;
+----+---------+-----------+
| id | name | parent_id |
+----+---------+-----------+
| 3 | Leader1 | 2 |
| 6 | Leader2 | 2 |
+----+---------+-----------+
显然不对,因为缺少了employee信息
a) 想到了一种办法,使用过算法来的,就增加一个employee_id字段,包含所有父节点的employee_id信息,在查找时直接通过计算得到。
ALTER TABLE table_employees ADD COLUMN employee_id int(4) NOT NULL DEFAULT 0;
查询Manage1下的所有员工:
SELECT * FROM table_employees WHERE employee_id like ‘11%‘ AND id <> 2;
+----+-----------+-----------+-------------+
| id | name | parent_id | employee_id |
+----+-----------+-----------+-------------+
| 3 | Leader1 | 2 | 111 |
| 4 | employee1 | 3 | 1111 |
| 5 | employee2 | 3 | 1112 |
| 6 | Leader2 | 2 | 112 |
| 7 | employee3 | 6 | 1121 |
| 8 | employee4 | 6 | 1122 |
+----+-----------+-----------+-------------+
这个方法可以,但是需要在设计表和插入数据的时候就计算好employee_id,对于老系统,没有这个字段的怎么处理呢?
b) 链接查询
SELECT t1.* FROM table_employees t1 INNER JOIN table_employees t2 ON t2.id = t1.parent_id WHERE t1.parent_id = 2 UNION ...
估计要用存储过程了...
标签:sql 组织结构
原文地址:http://power9li.blog.51cto.com/8267716/1567688