我有一個 目錄表 和 一個關系表。
目錄表里面存 所有的目錄資訊。CAT_ID, CAT_NAME,CAT_TYPE...
關系表里面存 一級目錄和對應的子目錄。CAT_LEAD, CAT_GROUPED。
我想要實作根據入參搜索符合要求的目錄。
如果一級目錄符合要求,結果里要排除它對應的子目錄。
如果一級目錄不符合要求,回傳包括子目錄在內的符合要求的目錄。
ex:
CAT_ID CAT_NAME CAT_TYPE
1 CAT1 A
2 CAT2 A
3 CAT3 B
4 CAT4 A
5 CAT5 A
CAT_LEAD CAT_GROUPED
1 2
3 4
如果我的搜索條件是CAT_TYPE = A
那么回傳的結果是1,4,5.
對目錄表查詢時的引數比較多,join了很多其他表。
請問有什么比較好的寫法能實作這個功能,不增加太多執行時間嗎?
uj5u.com熱心網友回復:
with tab1 as (
select 1 id, 'c1' nam, 'a' typ from dual union all
select 2 id, 'c2' nam, 'a' typ from dual union all
select 3 id, 'c3' nam, 'b' typ from dual union all
select 4 id, 'c4' nam, 'a' typ from dual union all
select 5 id, 'c5' nam, 'a' typ from dual
)
, tab2 as (
select 1 par, 2 children from dual union all
select 3, 4 from dual union all
select 3, 5 from dual
)
, tab3 as (
select*from tab1 t1, tab2 t2
where 1 = 1
and t1.id = t2.children(+)
)
select *
from tab3 t1
where 1 = 1
and t1.typ = 'a'
start with t1.par is null
connect by prior t1.id = t1.par
and (level = 2 and prior t1.typ != 'a')
;
除非你的關系是上下級多對多的關系,否則“關系表”是多余的,應該合并到“目錄表”中。你現在只有一個層級可能感覺不出來,層級多了之后都要像tab3那樣處理一下。
uj5u.com熱心網友回復:
思路:1、為目錄表增加欄位parent_id
2、找出每個parent_id的min(cat_id) where cat_type=用戶輸入的值
3、min(cat_id)就是我們要的結果
sql:
select c.parent_id,min(c.cat_id) as cat_id from
(
select a.cat_id,a.cat_name,a.cat_type,
case when a.cat_id = b.cat_grouped then b.cat_lead
else cat_id end as parent_id
from 目錄表 a,關系表 b
) c
where cat_type=用戶輸入的值
group by c.parent_id
uj5u.com熱心網友回復:
謝謝,不過我的過濾條件太多了,用起來也并不方便
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/48195.html
標籤:開發
上一篇:這個問題怎么解決,轉移表空間檔案有錯誤,然后登陸不上
下一篇:求鄭州ocp培訓機構!
