---
title: "有关读数据库的无刷新的三级联动以及层次数据(树形结构)在关系数据库的存储"
author: "syhan"
date: "2007-04-11T11:26:55Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2007-04-11T11:26:55Z"
id: 70002
url: "https://syhan.iteye.com/blog/70002"
---

我的标题真冗长：P

最近一直在考虑这个问题，如何在现在常用的关系型数据库（如mysql，mssql）中存储含有层次结构（例如xml或者树型结构）的数据，我最终要实现的结果是一个比较好的页面三级联动菜单。比较了一下现有的三级联动，无非有两种解决方案，1、将所有数据写成静态的，这样的缺点在于对更新封闭;2、每改变一次去数据库中获取数据，填充到下一级菜单，这个缺点是对数据库的开销比较大，查询一次数据要对数据库做三次操作，而且数据库设计的比较丑陋。上述两种方法都让我比较不能接受。

我想的是一种比较优雅的解决方案：在数据库中存储的数据不要冗余，便于查询，不要产生递归，对数据库的开销要尽可能的小，尽量做到一次将所有数据都读出来，用户也要有比较好的体验。我最初的解决方案就是用xml来存储联动的数据，但是对于数据库操作来说，最后还是要落实到对文件的I/O操作，从这方面来讲，使用xml和数据库并没有什么本质的不同。另外一种解决方案就是在关系数据库中存类xml的数据了。google了半天，最后发现了一片自己学院一位学长翻译的文章[www.nirvanastudio.org/category/database](http://www.nirvanastudio.org/category/database)，讲得就是如何在关系型数据库存储这种层次数据的。文中提出了两种解决方案，一是“邻接列表模型”或称为“递归方法”，这种存在着数据冗余，而且递归出于众所周知的原因，效率不高。第二种方法，也就是我现在采用的方法是"前序优先遍历"，表结构也很简单，没有冗余

id name left right

我觉得应该属于一种深度优先。通过每个节点的左右两个属性获得其子女的属性，好处就在于获得一个或几个节点只需要一次查询，而在更新的时候速度会比较慢，因为要更新多个后继节点，不过话说回来，更新相对于获取来说次数要少的多，可以忽略。

下面是我的解决方案：

java 代码

 

001. import java.io.IOException;
002. import java.sql.Connection;
003. import java.sql.ResultSet;
004. import java.sql.SQLException;
005. import java.sql.Statement;
006. import java.util.ArrayList;
007. import com.netkc.struts.datasource.DataSource;
008. import com.netkc.struts.mapping.District;
009. /\**
010. * @author SONG Yihan
011. * @version 1.0
012. * @date: Monday, April 09 2007
013. \*/
014. public class DistrictTree {
015. private ArrayList&lt;district&gt; tree;  &lt;/district&gt;
016. private Statement stmt1 = null;
017. private Statement stmt2 = null;
018. private Connection conn = null;
019. private ResultSet rs = null;
020. public DistrictTree() {
021. try {
022. conn = DataSource.getConnection();
023. } catch (IOException e) {
024. // TODO Auto-generated catch block
025. e.printStackTrace();
026. } catch (SQLException e) {
027. // TODO Auto-generated catch block
028. e.printStackTrace();
029. } catch (ClassNotFoundException e) {
030. // TODO Auto-generated catch block
031. e.printStackTrace();
032. } catch (InstantiationException e) {
033. // TODO Auto-generated catch block
034. e.printStackTrace();
035. } catch (IllegalAccessException e) {
036. // TODO Auto-generated catch block
037. e.printStackTrace();
038. }
039. }
040. public DistrictTree(Connection conn) {
041. this.conn = conn;
042. }
043. public boolean addNode(String parentId, String districtId, String districtName) {
044. try {
045. String sql = "SELECT * FROM district WHERE districtId='" + parentId + "';";
046. conn.setAutoCommit(false);
047. stmt1 = conn.createStatement();
048. rs = stmt1.executeQuery(sql);
049. if(rs.next()) {
050. int right = rs.getInt("rgt");
051. sql = "UPDATE district SET lft=lft+2 WHERE lft&gt;=" + right;
052. stmt2.addBatch(sql);
053. sql = "UPDATE district SET rgt=rgt+2 WHERE rgt&gt;=" + right;
054. stmt2.addBatch(sql);
055. sql = "INSERT INTO district (districtId, districtName, lft, rgt) VALUES ('"+districtId + "', '" + districtName + "', " +
056. (right) + ", " + (right+1) +");";
057. stmt2.addBatch(sql);
058. int\[] flag = stmt2.executeBatch();
059. if(flag\[flag.length - 1] == 1) {
060. conn.commit();
061. return true;
062. } else {
063. conn.rollback();
064. return false;
065. }
066. }
067. } catch (SQLException e) {
068. // TODO Auto-generated catch block
069. e.printStackTrace();
070. } finally {
071. }
072. return false;
073. }
074. public boolean deleteNode(String districtId) {
075. String sql = "SELECT * FROM district WHERE districtId='" + districtId + "';";
076. try {
077. conn.setAutoCommit(false);
078. rs = stmt1.executeQuery(sql);
079. if(rs.next())
080. {
081. int left = rs.getInt("lft");
082. int right = rs.getInt("rgt");
083. int count = (right - left - 1) / 2 + 1;
084. int minus = count * 2;
085. sql = "DELETE FROM district WHERE lft BETWEEN " + left + " AND " + right + ";";
086. stmt2.addBatch(sql);
087. sql = "UPDATE district SET lft=lft-" + minus + " WHERE lft&gt;"+right;
088. stmt2.addBatch(sql);
089. sql = "UPDATE district SET rgt=rgt-" + minus + " WHERE rgt&gt;"+right;
090. stmt2.addBatch(sql);
091. int flag = stmt2.executeBatch()\[0];
092. if(flag == 1) {
093. conn.commit();
094. return true;
095. } else {
096. conn.rollback();
097. return false;
098. }
099. }
100. } catch (SQLException e) {
101. // TODO Auto-generated catch block
102. e.printStackTrace();
103. }
104. return false;
105. }
106. public void displayTree(String parentId) {
107. }
108. public ArrayList&lt;district&gt; getTree(String parentId) {  &lt;/district&gt;
109. String sql = "SELECT * FROM district WHERE districtId='" + parentId + "';";
110. try {
111. stmt1 = conn.createStatement();
112. rs = stmt1.executeQuery(sql);
113. if(rs.next()) {
114. int left = rs.getInt("lft");
115. int right = rs.getInt("rgt");
116. stmt2 = conn.createStatement();
117. sql = "SELECT * FROM district WHERE lft BETWEEN " + left + " AND " + right + " ORDER BY lft ASC";
118. rs = stmt2.executeQuery(sql);
119. tree = new ArrayList&lt;district&gt;();  &lt;/district&gt;
120. District district = null;
121. while(rs.next()) {
122. district = new District();
123. district.setDistrictId(rs.getString("districtId"));
124. district.setDistrictName(rs.getString("districtName"));
125. district.setLeft(rs.getInt("lft"));
126. district.setRight(rs.getInt("rgt"));
127. tree.add(district);
128. }
129. return tree;
130. }
131. } catch (SQLException e) {
132. // TODO Auto-generated catch block
133. e.printStackTrace();
134. } finally {
135. try {
136. if (rs != null) {
137. rs.close();
138. }
139. stmt1.close();
140. stmt2.close();
141. conn.close();
142. } catch (SQLException e) {
143. // TODO Auto-generated catch block
144. e.printStackTrace();
145. }
146. }
147. return null;
148. }
149. public ArrayList&lt;district&gt; getChildren(String parentId) {  &lt;/district&gt;
150. if(tree == null) {
151. tree = getTree(parentId);
152. }
153. ArrayList&lt;district&gt; children = new ArrayList&lt;district&gt;();  &lt;/district&gt;&lt;/district&gt;
154. int index = this.indexof(parentId);
155. if(index != -1) {
156. District d = tree.get(index);
157. final int count = (d.getRight() - d.getLeft() - 1) / 2;
158. for(int i = index + 1; i &lt;= index + count; i++) {
159. d = tree.get(i);
160. children.add(d);
161. i += (d.getRight() - d.getLeft() - 1) / 2;
162. }
163. }
164. return children;
165. }
166. private int indexof(String districtId) {
167. for(int index = 0; index &lt; tree.size(); index++) {
168. if(districtId.equals(tree.get(index).getDistrictId())) {
169. return index;
170. }
171. }
172. return -1;
173. }
174. public boolean updateNode(String districtId, String districtName) {
175. String sql = "UPDATE district SET districtName='" + districtName + "' WHERE districtId='" + districtId + "';";
176. try {
177. conn.setAutoCommit(false);
178. stmt1 = conn.createStatement();
179. int flag = stmt1.executeUpdate(sql);
180. if(flag == 1) {
181. conn.commit();
182. return true;
183. }
184. else {
185. conn.rollback();
186. return false;
187. }
188. } catch (SQLException e) {
189. // TODO Auto-generated catch block
190. e.printStackTrace();
191. } finally {
192. }
193. return false;
194. }
195. }

这个最遗憾的地方就是在其中混杂了java代码，这让我及其不爽，但是我没有找到向js传值的好办法：（

js 代码

 

01. function District(id, name, left, right) {
02. this.id=id;
03. this.name=name;
04. this.left=left;
05. this.right=right;
06. };
07. var tree = new Array();
08. &lt;%
09. for(District d : tree) {
10. %&gt;  tree.push(new District('&lt;%=d.getDistrictId()%&gt;', '&lt;%=d.getDistrictName()%&gt;', '&lt;%=d.getLeft()%&gt;', '&lt;%=d.getRight()%&gt;'));
11. &lt;%}%&gt;
12. Array.prototype.indexof = function(id) {
13. for(var index = 0; index &lt; tree.length; index++) {
14. if(id == tree\[index].id) {
15. return index;
16. }
17. }
18. return -1;
19. };
20. function citychanged(id){
21. document.getElementById('district').length = 0;
22. document.getElementById('area').length = 0;
23. var districts = getChildren(id);
24. for(var i = 0; i &lt; districts.length; i++){
25. document.getElementById('district').options\[i] = new Option(districts\[i].name, districts\[i].id);
26. }
27. };
28. function districtchanged(id) {
29. document.getElementById('area').length = 0;
30. var area = getChildren(id);
31. for(var i = 0; i &lt; area.length; i++){
32. document.getElementById('area').options\[i] = new Option(area\[i].name, area\[i].id);
33. }
34. };
35. function getChildren(id) {
36. if(tree.length == 0) {
37. }
38. var children = new Array();
39. var index = tree.indexof(id);
40. if(index != -1) {
41. var d = tree\[index];
42. var count = (d.right - d.left - 1) / 2;
43. for(var i = index + 1; i &lt;= index + count; i++) {
44. d = tree\[i];
45. children.push(d);
46. i += (d.right - d.left - 1) / 2;
47. }
48. }
49. return children;
50. };

 

jsp 页面 代码

 

1. "/fastfoodAct?method=query" styleId="queryFoodForm"&gt;
2. searchType :
3. city :
4. district :
5. area :
6. restaurantName :
7. searchType :
8. foodName :
9. &lt;html:submit&gt; &lt;html:cancel&gt;    &lt;/html:cancel&gt; &lt;/html:submit&gt;

 

以上就是我解决三级联动和层次结构的一点想法：）