关于一个树形结构对于数据库的查询

    技术2022-05-19  28

    通常我们在做页面树查询数据库的时候,通过对一张表的重复递归,可以查询出表中的所有分类,这种方法确实可以递归出表中的所有节点分类,但是不断的递归会造成不必要的一些问题,这里有一个比较经典的关于对数据库中,树状结构的查询,如下:表的创建:

    create table category

    (

      id varchar(40) primary key,

      name varchar(100),

      lft int, --代表节点的左数值

      rgt int --代表节点的右数值

    )

    插入数据如下:

    insert into category values('1','商品',1,18);

    insert into category values('2','平板电视',2,7);

    insert into category values('3','冰箱',8,11);

    insert into category values('4','笔记本',12,17);

    insert into category values('5','长虹',3,4);

    insert into category values('6','索尼',5,6);

    insert into category values('7','西门子',9,10);

    insert into category values('8','thinkpad',13,14);

    insert into category values('9','dell',15,16);

    首先我们使用表的自连接查询,将这张表看做两张表:

    Select * from category parent, category child;

    我们发现,在我们所设计的树中,孩子节点的左数值永远大于父亲节点的左数值,孩子节点的右数值永远小于父亲节点的右数值,通过如下语句,我们可以得到父亲的所有孩子

    Select * from category parent, category child where child.lft>parent.lft and child.rgt<parent.rgt;

    我们通过对孩子们进行归类,就可以根据一个孩子归类的次数来获取这个孩子位于树的那一层,例如,一个孩子归类两次,说明他有两个父亲,就可以得到这个孩子的层数depth

    Select child.name,count(child.name) depthfrom category parent, category child where child.lft>parent.lft and child.rgt<parent.rgt group by child.name

    最后我们通过左数值进行排序,就可以实现页面效果了:

    Select child.name,count(child.name) depthfrom category parent, category child where child.lft>parent.lft and child.rgt<parent.rgt group by child.name order by child.lft

    这种结构在查询的过程中,并没有使用递归,并且也能够高效的查询出所有的节点分支,在用来做树的时候,是很不错的选择。


    最新回复(0)