【发布时间】:2020-08-31 18:41:56
【问题描述】:
我的架构如下所示。
我有等级区:
create table district(
id integer primary key,
name varchar2(32),
parent_id integer references district(id)
)
以及地区内的房屋:
create table house(
id integer primary key,
name varchar2(32),
district_id integer references district(id)
)
house.district_id始终位于district 层次结构的底部。如何选择districts 层次结构的根 的每个房子和id 和name?
目前我正在使用两个子查询,但感觉不对:
select
h.id,
h.name,
(
select id from district
where parent_id is null
start with id = house.district_id
connect by parent_id = id
) as district_id,
(
select name from district
where parent_id is null
start with id = house.district_id
connect by parent_id = id
) as district_name
from house;
Oracle 版本为 11g 第 2 版。
样本数据: 地区
+-------------------+
| id name parent_id |
+-------------------+
| 1 'one' NULL |
| 2 'two' 1 |
| 3 'three' 3 |
+-------------------+
房子
id name district_id
1 'h1' 3
2 'h2' 3
3 'h3' 3
期望的输出:
+------------------------------------+
| id name district_id, district_name |
+------------------------------------+
| 1 'h1' 1 'one' |
| 2 'h2' 1 'one' |
| 3 'h3' 1 'one' |
+------------------------------------+
【问题讨论】:
-
你有样本数据和预期结果吗。
-
SQLFiddle 现在对我不起作用。我会尝试使用 ASCII 表提供示例数据:)
标签: sql oracle oracle11g recursive-query hierarchical-query