2015-04-22 38 views
4

我研究了這一點,知道我不是第一個問,但我似乎無法得到我的頭。我創建了一個簡單的例子,如果有人能夠提供缺失的鏈接,我認爲這將幫助我破解它!加入兩個分層查詢形成較大的層次

我有一個包含大陸和國家層次結構的區域表。

我也有一張地方表,包含層次結構中的城市和地標。此表包含要加入區域表的區域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 

就是有人能告訴我最後一步加入到這些一個查詢與四個級別?我已經與甲骨文合作多年,但不知何故,這從來沒有出現!

如果在地點表中沒有先前的連接,只需要一個區號爲id的城市列表,這會更容易嗎?

謝謝

回答

2

是您需要的嗎?

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 
+0

解決了我問的問題,謝謝!我會盡快標記爲正確的。 我對地點表中沒有層次結構的情況進行了編輯 - 這是否會改變您如何處理此問題? 再次感謝。 –

+0

不,它不會。通常,如果您希望使用'connect by',則應將所有行合併到一個記錄集中。我用負面id的技巧,但沒有必要。你可以使連接更加精確,比如'type = prior type和parent_id = prior id' –

+0

非常好,謝謝你的幫助:) –