select * from area
where area_level=3
connect by prior area.area_id = area.parent_id;
select * from area
start with area_level=3
connect by prior area.area_id = area.parent_id;
为什么第一个sql 遍历了三遍
付建表语句
create table AREA
(
area_id VARCHAR2(50) not null,
area_name VARCHAR2(200) not null,
area_level VARCHAR2(50),
parent_id VARCHAR2(50) not null
);
comment on column AREA.area_id
is '地区编码';
comment on column AREA.area_name
is '地区名称';
comment on column AREA.area_level
is '级别(省/直辖市=1,地级市/盟=2,县级市/旗=3)';
comment on column AREA.parent_id
is '父地区ID';
insert into AREA (area_id, area_name, area_level, parent_id)
values ('010101', '北京', '3', '0101');
insert into AREA (area_id, area_name, area_level, parent_id)
values ('010102', '海淀', '3', '0101');
insert into AREA (area_id, area_name, area_level, parent_id)
values ('010103', '朝阳', '3', '0101');
insert into AREA (area_id, area_name, area_level, parent_id)
values ('010104', '顺义', '3', '0101');
insert into AREA (area_id, area_name, area_level, parent_id)
values ('010105', '怀柔', '3', '0101');
insert into AREA (area_id, area_name, area_level, parent_id)
values ('010106', '通州', '3', '0101');
insert into AREA (area_id, area_name, area_level, parent_id)
values ('010107', '昌平', '3', '0101');
insert into AREA (area_id, area_name, area_level, parent_id)
values ('010108', '延庆', '3', '0101');
insert into AREA (area_id, area_name, area_level, parent_id)
values ('010109', '丰台', '3', '0101');
insert into AREA (area_id, area_name, area_level, parent_id)
values ('01', '北京', '1', '0');
insert into AREA (area_id, area_name, area_level, parent_id)
values ('0101', '北京', '2', '01');
insert into AREA (area_id, area_name, area_level, parent_id)
values ('010110', '石景山', '3', '0101');
insert into AREA (area_id, area_name, area_level, parent_id)
values ('010111', '大兴', '3', '0101');
insert into AREA (area_id, area_name, area_level, parent_id)
values ('010112', '房山', '3', '0101');
insert into AREA (area_id, area_name, area_level, parent_id)
values ('010113', '密云', '3', '0101');
insert into AREA (area_id, area_name, area_level, parent_id)
values ('010114', '门头沟', '3', '0101');
insert into AREA (area_id, area_name, area_level, parent_id)
values ('010115', '平谷', '3', '0101');
------解决方案--------------------
START WITH 被省略,则表示所有满足查询条件的行作为根节点。
------解决方案--------------------
为什么第一个sql 遍历了三遍
以‘海淀’为例:
01012 -> 0101 ->01
------解决方案--------------------
重写一下SQL,看看是否更有利于你理解
select * from
(select * from area
connect by prior area.area_id = area.parent_id) ss
where ss.area_level=3 and ss.area_name='海淀';
语句是先执行 connect by prior 然后执行 WHERE
------解决方案--------------------
用01 北京 循环一次
用 0101 北京 循环一次
所有人做root 再循环一次