一、建表及插入数据
ocation_id | location_name | parent_location_id |
---|---|---|
1 | 广东省 | NULL |
2 | 广州市 | 1 |
3 | 深圳市 | 1 |
4 | 天河区 | 2 |
5 | 番禺区 | 2 |
6 | 南山区 | 3 |
7 | 宝安区 | 3 |
建表sql:
sql
CREATE TABLE locations (
location_id NUMBER PRIMARY KEY,
location_name VARCHAR2(100),
parent_location_id NUMBER
);
INSERT INTO locations (location_id, location_name, parent_location_id)
VALUES (1, '广东省', NULL);
INSERT INTO locations (location_id, location_name, parent_location_id)
VALUES (2, '广州市', 1);
INSERT INTO locations (location_id, location_name, parent_location_id)
VALUES (3, '深圳市', 1);
INSERT INTO locations (location_id, location_name, parent_location_id)
VALUES (4, '天河区', 2);
INSERT INTO locations (location_id, location_name, parent_location_id)
VALUES (5, '番禺区', 2);
INSERT INTO locations (location_id, location_name, parent_location_id)
VALUES (6, '南山区', 3);
INSERT INTO locations (location_id, location_name, parent_location_id)
VALUES (7, '宝安区', 3);
二、展现出省市县之间的层级结构
sql:
sql
SELECT location_id, location_name, LEVEL
FROM locations
CONNECT BY PRIOR location_id = parent_location_id
START WITH parent_location_id IS NULL;
结果:
location_id | location_name | LEVEL |
---|---|---|
1 | 广东省 | 1 |
2 | 广州市 | 2 |
4 | 天河区 | 3 |
5 | 番禺区 | 3 |
3 | 深圳市 | 2 |
6 | 南山区 | 3 |
7 | 宝安区 | 3 |
三、每个区域在层级结构中的完整路径
sql:
sql
SELECT location_id,
location_name,
LEVEL,
SYS_CONNECT_BY_PATH(location_name,'/') AS path
FROM locations
CONNECT BY PRIOR location_id = parent_location_id
START WITH parent_location_id IS NULL;
结果:
location_id | location_name | LEVEL | path |
---|---|---|---|
1 | 广东省 | 1 | 广东省 |
2 | 广州市 | 2 | 广东省/广州市 |
4 | 天河区 | 3 | 广东省/广州市/天河区 |
5 | 番禺区 | 3 | 广东省/广州市/番禺区 |
3 | 深圳市 | 2 | 广东省/深圳市 |
6 | 南山区 | 3 | 广东省/深圳市/南山区 |
7 | 宝安区 | 3 | 广东省/深圳市/宝安区 |