---
title: "Oracle的多表树查询"
author: "sshzhangwg"
date: "2013-04-11T16:22:13Z"
tags: ["Oracle", "地区", "树查询"]
categories: ["数据库"]
slug: "oracle"
draft: false
lastmod: "2013-04-11T16:23:42Z"
id: 1845846
url: "https://aiappfine.iteye.com/blog/1845846"
---

地区是树形结构，地区下面还有结构，即机构表中有一个地区ID字段。要把这两个东西组织在一起，挂在一棵树上。刚开始想得有点复杂了，先查出地区树然后遍历出每个地区下面的机构，再绑定这种关系。马上否决了这个想法，因为 1、很复杂 2、性能慢会成为大问题。

    实际上很简单的，我们把问题想复杂了，下面我贴出SQL，看下就明白了：

 

```
select *
  from (select area_id as id,
               area_name as text,
               area_parentid as pid,
               '0' as isOrg,
               'false' as isexpand
          from d_area a
        union
        select id,
               orgname as text,
               area_id as pid,
               '1' as isOrg,
               'false' as isexpand
          from ac_org b) t
 start with t.id = '49'
connect by t.pid = prior t.id;
```