---
title: "递归遍历树形结构及数据库设计"
author: "QuarterLifeForJava"
date: "2015-07-07T09:13:36Z"
tags: []
categories: ["数据库"]
slug: "untitled"
draft: false
lastmod: "2015-11-10T14:37:46Z"
id: 2224839
url: "https://quarterlifeforjava.iteye.com/blog/2224839"
---

```java

public class Test {
	
	public static void main(String[] args) {
		Map<Integer,Integer> map = new HashMap<Integer,Integer>();
		map.put(1, 0);
		map.put(2, 0);
		map.put(3, 1);
		map.put(4, 1);
		map.put(5, 2);
		map.put(6, 4);
		map.put(7, 4);
		map.put(8, 7);
		//得到某一节点下的所有子节点(如果有)
		getIds(1, map);
		System.out.println(listRet);
	}
	
	private static List<Integer> listRet = new ArrayList<Integer>();
	public static void getIds(int id,Map<Integer,Integer> map){
		List<Integer> list = new ArrayList<Integer>();
		for (int i = 0; i < map.size(); i++) {
			int x = map.get((i+1));
			if(x==id){
				list.add((i+1));
			}
		}
		if(list.size()!=0){
			listRet.addAll(list);
			System.out.println(id+"->"+list);
			for (int i = 0; i < list.size(); i++) {
				getIds(list.get(i), map);
			}
		}
	}

}

```

![](http://dl2.iteye.com/upload/attachment/0110/0068/d33a5149-4430-3b92-a118-e51020362642.png)
数据库设计：
![](http://dl2.iteye.com/upload/attachment/0112/3044/1ce1360a-9746-3bfd-9322-3e04d9c75b5c.png)

![](http://dl2.iteye.com/upload/attachment/0112/3046/8e7fdd5f-7c8c-3b70-a7b9-c0ce677cefa9.png)

查询语句为：

```sql

SELECT * from tree WHERE
position REGEXP CONCAT((SELECT position from tree where name = 'fruit'),'[\w\w]*')

```

当然，你用like也可以
查询结果为：
![](http://dl2.iteye.com/upload/attachment/0112/3048/e55b3f89-1abe-33a0-907a-c892b8ddc1f3.png)
如果要插入的话略有一点复杂，步骤为：
如当我要在id=36的banana边插入一个同级的，做法为：
1、先获得blue的position，为1-1-2
2、找到1-1-2*匹配的正则，获取最后一段，按降序排列，得到第一个的数字
3、将数字+1，并拼装1-1-2为最终结果