mysql 几种树的结构_发现几种树结构数据库存储方案

最近在开发jSqlBox过程中,研究树形结构的操作,突然发现一种新的树结构数据库存储方案,在网上找了一下,没有找到雷同的(也可能是花的时间不够),现介绍如下: 目前常见的树形结构数据库存储方案有以下四种,但是都存在一定问题:

1)Adjacency List::记录父节点。优点是简单,缺点是访问子树需要遍历,发出许多条SQL,对数据库压力大。

2)Path Enumerations:用一个字符串记录整个路径。优点是查询方便,缺点是插入新记录时要手工更改此节点以下所有路径,很容易出错。

3)Closure Table:专门一张表维护Path,缺点是占用空间大,操作不直观。

4)Nested Sets:记录左值和右值,缺点是复杂难操作。

以上方法都存在一个共同缺点:操作不直观,不能直接看到树结构,不利于开发和调试。

本文介绍的方法我暂称它为“简单粗暴多列存储法”,它与Path Enumerations有点类似,但区别是用很多的数据库列来存储一个占位符(1或空值),如下图(https://github.com/drinkjava2/Multiple-Columns-Tree/blob/master/treemapping.jpg) 左边的树结构,映射在数据库里的结构见右图表格:

af61a1e6cc0bc7a82052691840647a6b.png

各种SQL操作如下:

1.获取(或删除)指定节点下所有子节点,已知节点的行号为"X",列名"cY":

select *(or delete) from tb where

line>=X and lineX and (cY=1 or c(Y-1)=1 or c(Y-2)=1 ... or c1=1))

例如获取D节点及其所有子节点:

select * from tb where line>=7 and line< (select min(line) from tb where line>7 and (c2=1 or c1=1))

删除D节点及其所有子节点:

delete from tb where line>=7 and line< (select min(line) from tb where line>7 and (c2=1 or c1=1))

仅获取D节点的次级所有子节点:

select * from tb where line>=7 and c3=1 and line< (select min(line) from tb where line>7 and (c2=1 or c1=1))

2.查询指定节点的根节点, 已知节点的行号为"X",列名"cY":

select * from tb where line=(select max(line) from tb where line<=X and c1=1)

例如查I节点的根节点:

select * from tb where line=(select max(line) from tb where line<=12 and c1=1)

3.查询指定节点的上一级父节点, 已知节点的行号为"X",列名"cY":

select * from tb where line=(select max(line) from tb where line

例如查L节点的上一级父节点:

select * from tb where line=(select max(line) from tb where line<11 and c3=1)

3.查询指定节点的所有父节点, 已知节点的行号为"X",列名"cY":

select * from tb where line=(select max(line) from tb where line

union select * from

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值