表看起來有點像:的Oracle 11g分層查詢需要一定的遺傳數據
create table taco (
taco_id int primary key not null,
taco_name varchar(255),
taco_prntid int,
meat_id int,
meat_inht char(1) -- inherit meat
)
數據是這樣的:
insert into taco values (1, '1', null, 1, 'N');
insert into taco values (2, '1.1', 1, null, 'Y');
insert into taco values (3, '1.1.1', 2, null, 'N');
insert into taco values (4, '1.2', 1, 2, 'N');
insert into taco values (5, '1.2.1', 4, null, 'Y');
insert into taco values (6, '1.1.2', 2, null, 'Y');
或...
- 1 has a meat_id=1
- 1.1 has a meat_id=1 because it inherits from its parent via taco_prntid=1
- 1.1.1 has a meat_id of null because it does NOT inherit from its parent
- 1.2 has a meat_id=2 and it does not inherit from its parent
- 1.2.1 has a meat_id=2 because it does inherit from its parent via taco_prntid=4
- 1.1.2 has a meat_id=1 because it does inherit from its parent via taco_prntid=2
現在...我在世界上如何查詢meat_id
是什麼每個taco_id
?下面是什麼工作,直到我意識到我沒有使用繼承標誌,我的一些數據搞亂了。
select x.taco_id,
x.taco_name,
to_number(substr(meat_id,instr(rtrim(meat_id), ' ', -1)+1)) as meat_id
from ( select taco_id,
taco_name,
level-1 "level",
sys_connect_by_path(meat_id, ' ') meat_id
from taco
start with taco_prntid is null
connect by prior taco_id = taco_prntid
) x
我可以發佈一些失敗的嘗試來修改上面的查詢,但他們是相當尷尬的失敗。在超出基本範圍之前,我還沒有用過分層查詢,所以我希望有一些關鍵字或概念我不知道應該搜索。
我在底部張貼了一個答案,以表明我最終結束了什麼。我正在接受另一個被接受的答案,因爲他們能夠使我的數據更加清晰,沒有它,我不會得到任何地方。
這是否對你有幫助? http://sqlfiddle.com/#!4/642482/2 –