sql - 加入两个 Hierarchical 查询以形成更大的 Hierarchy

标签 sql oracle hierarchical-data recursive-query

我已经对此进行了研究,并且知道我不是第一个提出问题的人,但我似乎无法理解它。我创建了一个简单的示例,如果有人可以提供缺失的链接,我认为它可以帮助我破解它!

我有一个区域表,其中包含层次结构中的大陆和国家。

我还有一个地点表,其中包含层次结构中的城市和地标。该表包含一个区域 id 列以连接到区域表。

    create table areas
(
  id            NUMBER not null,
  name          VARCHAR2(200) not null,
  parent_id     NUMBER
);

-- Top Level
Insert into areas (id, name)
 Values (1, 'Europe');
Insert into areas (id, name)
 Values (2, 'Americas');
Insert into areas (id, name)
 Values (3, 'Asia ex Japan');
Insert into areas (id, name)
 Values (4, 'Japan');

 -- Jurisdictions
Insert into areas (id, name, parent_id)
 Values (5, 'UK', 1);
Insert into areas (id, name, parent_id)
 Values (7, 'France', 1);
Insert into areas (id, name, parent_id)
 Values (6, 'Germany', 1);
Insert into areas (id, name, parent_id)
 Values (8, 'Italy', 1);
Insert into areas (id, name, parent_id)
 Values (9, 'US', 2);
Insert into areas (id, name, parent_id)
 Values (10, 'Australia', 3);
Insert into areas (id, name, parent_id)
 Values (11, 'New Zealand', 3);

create table places
(
  id            NUMBER not null,
  name          VARCHAR2(200) not null,
  area_id       NUMBER,
  parent_id     NUMBER
);

Insert into places (id, name, area_id, parent_id)
 Values (1, 'London', 5, NULL);
Insert into places (id, name, area_id, parent_id)
 Values (2, 'Bath', 5, NULL);
Insert into places (id, name, area_id, parent_id)
 Values (3, 'Liverpool', 5, NULL);
Insert into places (id, name, area_id, parent_id)
 Values (4, 'Paris', 7, NULL);
Insert into places (id, name, area_id, parent_id)
 Values (5, 'New York', 9, NULL);
Insert into places (id, name, area_id, parent_id)
 Values (6, 'Chicago', 9, NULL);
Insert into places (id, name, area_id, parent_id)
 Values (7, 'Kings Cross', 5, 1);
Insert into places (id, name, area_id, parent_id)
 Values (8, 'Tower of London', 5, 1);

我可以像这样独立查询这些表:
 SELECT a.*, level FROM areas a
start with parent_id is null
connect by prior id = parent_id

SELECT p.*, level FROM places p
start with parent_id is null
connect by prior id = parent_id

有人能够向我展示将这些加入一个具有四个级别的查询的最后一步吗?我已经与 Oracle 合作多年,但不知何故从未出现过!

如果在places 表中没有connect by 之前,只有一个带有区域ID 的城市列表,这会更容易吗?

谢谢

最佳答案

这是你需要的吗?

with src as (
  select 'A' type, a.id, a.name, a.parent_id, null area_id from areas a
  union all
  select 'P', -p.id id, p.name, -p.parent_id parent_id, area_id from places p)
select 
  src.*, level
from 
  src
start with 
  type = 'A' and parent_id is null
connect by 
  parent_id = prior id or 
  parent_id is null and area_id = prior id

关于sql - 加入两个 Hierarchical 查询以形成更大的 Hierarchy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29794055/

相关文章:

sql - 在数据库中搜索并替换部分字符串

mysql - SQL语法错误

java - 有人可以向我解释这个 JDBC 异常吗?

c# - 如何使用 ASP.net 3.5 和 LINQ 将数据库分层数据转换为 XML

sql - 是否有一个程序可以显示现有数据库中的 SQL 模式图?

mysql - 跨多个列计算唯一项目(颜色)

mysql - 层次结构、临时表插入自

c# - 获取自引用层次树中的最后一个 child

database - PL/SQL - 对嵌套自定义对象的集合进行排序

Oracle 时区转换(使用 from_tz)