◎筱米加步枪◎.Blog

Happy coding

Oracle 树状查询

筱米加步枪 posted @ 2010年8月18日 23:01 in [ 数据库 ] with tags oracle 树状 , 3194 阅读

在实际应用中,经常利用数据库保存树状结构的数据,通常用一张表中的两个字段表示,一个是自身的ID,一个是保存父类的ID。在这样具有这种关系中的数据,要求查出的数据具有我们想要的树状显示。这里需要引入Oracle的一个查询语句。

Select  *  from tablename
  start with [condition1]
  Connect By Prior  [condition2]
  where [condition3] 

condition1 通常是用于筛选某颗树或者多颗树的结点,这里所的树包括子树,

condtion2 通常是用于连接父结点和子结点的关系,prior 所表示的是上一条记录,通常用法:prior id = pid,(上一条的的ID号是本条记录的父类ID号)这样就把整个树状结构给建立起来了。

conditon3 就是我们通常的where语句,过滤某些记录。

现在看下具体例子。

其中Test_ID 表示本身的ID,Test_PID表示父类的ID

这边记录的描述成树状结构就是如下:

现在,假设我们查询的福州以及福州下的所有子东西,就可以这样查询,

只要取福州的根结点就可以,福州的根结点翻译成数据库中存的数据就是 test_id =1

因此得到的sql如下:

Select * From Test_ t 
  Start With Test_Id = 1
  Connect By Prior Test_Id = Test_Pid

查询结果:

用结构图表示就是如下信息:

因此想要查询某些信息,只要抓住根结点的条件就可以。。Over~~

Avatar_small
bigzhu 说:
2010年8月19日 02:57

呵呵,我正想写一篇 oracle 树状查询的呢,想不到你已经先写了
那我来扯一下对 prior 的理解..

Avatar_small
筱米加步枪 说:
2010年8月20日 23:48

@bigzhu: 大家互相学习嘛。。哈

pavzi.com 说:
2024年1月23日 19:42

Pavzi.com provides all the news about Gadgets, the Economy, Technology, Business, Finance and many more. The main concept or our aim behind this website has been the will to provide resources with full information on each topic which can be accessed through the Internet. To ensure that every reader gets what is important and worthy about the topic they search and link to hear from us. pavzi.com Our site is a multiple Niche or category website which will ensure to provide information and resources on each and every topic. Some of the evergreen topics you will see on our website are Career, Job Recruitment, Educational, Technology, Reviews and others. We are targeting mostly so it is true that Tech, Finance, and Product Reviews. The only reason we have started this website is to make this site the need for your daily search use.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter