數據庫中樹狀關系(各種樹狀分類)的查找
很多情況下,一些樹狀分類關系的都使用遞歸來查詢,用遞歸來顯示,如果數據量大的話,會造成各種麻煩。
我們可以使用樹,用先序遍歷來代替遞歸,如表:
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);
先序遍歷的順序圖:
可以發現規律:
- 如果一個節點存在子節點,那么右值與左值之差不為1;其所有子節點的的左右值均小于此節點的左右值。
- 反之則節點為葉節點。
在數據庫中的查詢語句如下:
select child.name,count(child.name) depth from category parent,category child where child.lft>=parent.lft and child.rgt<=parent.rgt group by child.name order by child.lft; --首先將一個表看成兩個表,一張是父節點,一張是子節點 --子節點的左值小于父節點的左值,右值小于父節點的右值,根據這個條件獲得存在關系的數據 --對子節點的name進行歸組,然后統計個數(count),這樣得到有幾個上級結點,也就是層次(depth) --最后,按照子節點的左值進行排序
這樣,會以很高的效率查詢出樹狀結構,避免了遞歸的缺點。
在交互層面,列舉一個jsp的js示例:
<html>
<head>
<title>樹狀結構</title>
<!-- 這里使用了xtree -->
<script src="${pageContext.request.contextPath }/js/xtree.js"></script>
<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath }/css/xtree.css">
</head>
<body>
<script type="text/javascript">
<c:forEach var="c" items="${list}">
//這是根結點
<c:if test="${c.depth==1}">
var tree = new WebFXTree('${c.name}');
tree.target="right";
tree.action = "${pageContext.request.contextPath}/servlet/AddChildServlet?id=${c.id}";
</c:if>
//這是二級結點
<c:if test="${c.depth==2}">
var node${c.depth} = new WebFXTreeItem('${c.name}');
node${c.depth}.target="right";
node${c.depth}.action = "${pageContext.request.contextPath}/servlet/AddChildServlet?id=${c.id}";
tree.add(node${c.depth});
</c:if>
//如果深度大于2級了,直接在node名稱上做手腳
<c:if test="${c.depth>2}">
var node${c.depth} = new WebFXTreeItem('${c.name}');
node${c.depth}.target="right";
node${c.depth}.action = "${pageContext.request.contextPath}/servlet/AddChildServlet?id=${c.id}";
node${c.depth-1}.add(node${c.depth});
</c:if>
</c:forEach>
document.write(tree);
</script>
</body>
</html>
![clip_image001[9] clip_image001[9]](https://images.cnblogs.com/cnblogs_com/hangxin1940/201106/201106282058338351.gif)
浙公網安備 33010602011771號