组织机构树数据库表设计

时间:2019-04-19 00:54:32   收藏:0   阅读:959

公司需要做一个组织机构管理的系统,但是现有的数据库中存储的方式,机构之间的关联只是通过parent_id关联的,这样在查询的时候需要不断的递归查询表数据,性能很差,逻辑也不清晰。所以在网上找到了几种针对这种树状结构存储,查询插入的优化方法

1.发现几种树结构数据库存储方案

2.聊聊树状结构如何在数据库中存储

3.组织机构树设计 

1.2两种有点复杂了,第三个连接有一位答主介绍了一种快捷查询的方法

 1 很麻烦的做法。
 2 简单的只需要在原表里加一列就行了:
 3 
 4 组织机构简洁字段设计:
 5 
 6 (ogran_code是组织机构唯一代码,真正的系统里都会有这东西的)
 7 
 8 id,name,ogran_code,parent_id
 9 
10 快速查询字段设计:
11 
12 id,name,ogran_code,parent_id,code_link
13 
14 (code_link是从根到该机构的整个code链条,例如: "root_code"+"first_code"+"child_code")
15 分隔符自定义即可
16 添加编辑机构时只关注该机构的父机构,在父机构的link上添加本机构的部分:  "pareat_code_link"+"local_code"
17 
18 任何查询都可以通过这个字段快速完成。
19 
20 1,某机构所有子机构,查询所有包含某机构CODE的CODE_LINK即可。可以使用like,超级简单。
21 2,查询Level,拆分该字段即可。
22 
23 总之,很方便记录的一个链路LINK,可以做到任意需要递归才可以完成的查询。

 

 

 用图表分析了一下

 

技术图片

  id  code_link

  1  0_null_null

  id  code_link

  1  0_null_2

  2  1_null_null

  id  code_link

  1  0_null_2,3

  2  1_null_null

  3  1_null_null

  id  code_link

  1  0_null_2,3

  2  1_null_4

  3  1_null_null

  4  1_2_null

  id  code_link

  1  0_null_2,3

  2  1_null_4,5

  3  1_null_null

  4  1_2_null

  5  1_2_null

  id  code_link

  1  0_null_2,3

  2  1_null_4,5

  3  1_null_6

  4  1_2_null

  5  1_2_null

  6  1_3_null

  id  code_link

  1  0_null_2,3

  2  1_null_4,5

  3  1_null_6,7

  4  1_2_null

  5  1_2_null

  6  1_3_null

  7  1_3_null

  id  code_link

  1  0_null_2,3

  2  1_null_4,5

  3  1_null_6,7

  4  1_2_8

  5  1_2_null

  6  1_3_null

  7  1_3_null

  8  1_2,4_null

  id  code_link

  1  0_null_2,3

  2  1_null_4,5

  3  1_null_6,7

  4  1_2_8,9

  5  1_2_null

  6  1_3_null

  7  1_3_null

  8  1_2,4_null

  9  1_2,4_null

  id  code_link

  1  0_null_2,3

  2  1_null_4,5

  3  1_null_6,7

  4  1_2_8,9

  5  1_2_null

  6  1_3_null

  7  1_3_null

  8  1_2,4_null

  9  1_2,4_10

  10   1_2,4,9_null

 

至此,查询一个机构的子机构只需查询root_code和first_code中含有此节点id的数据

例如,查询(2上海分公司)的子机构,则为4,5,8,9,10

查询(4徐汇办事处)的子机构,则为8,9,10


  

评论(0)
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!