樹形結構查詢

2021-09-02 04:08:06 字數 1618 閱讀 3546

select id, name

from (select substr(translate(sys_connect_by_path(translate(t.name,

'-',

'tmp_'),

'-'),

'tmp_',

'-'),

2) name,

t.id,

t.store_id

from allocations t

where t.store_id = 2301

connect by t.father_allocation_id = prior t.id

start with t.father_allocation_id is null)

1.語法:

translate(string,from_str,to_str)

示例sql**

1. select translate('abcdefghij','abcdef','123456') from dual;

2. translate (

3. --------------

4. 123456ghij

5.6. select translate('abcdefghij','abcdefghij','123456') from dual;

7. transl

8. ----------

9. 123456

補充說明

語法:translate(expr,from,to)

expr: 代表一串字元,from 與 to 是從左到右一一對應的關係,如果不能對應,則視為空值。

舉例:select translate('abcbbaadef','ba','#@') from dual (b將被#替代,a將被@替代)

select translate('abcbbaadef','bad','#@') from dual (b將被#替代,a將被@替代,d對應的值是空值,將被移走)

因此:結果依次為:@#c##@@def 和@#c##@@ef

語法:translate(expr,from,to)

expr: 代表一串字元,from 與 to 是從左到右一一對應的關係,如果不能對應,則視為空值。

2.其實sys_connect_by_path這個函式是oracle9i才新提出來的!

它一定要和connect by子句合用!

第乙個引數是形成樹形式的字段,第二個引數是父級和其子級分隔顯示用的分隔符!

start with 代表你要開始遍歷的的節點!

connect by prior 是標示父子關係的對應!

這個函式使用之前必須先建立乙個樹,否則無用

sys_connect_by_path(欄位名, 2個字段之間的連線符號),注意這裡的連線符號不要使用逗號,oracle會報錯,如果一定要用,可以使用replace替換一下,方法如下 replace(欄位名,原字元,',')。

樹: start with 條件1 connect by prior 條件2

條件1如 子=xx (或父=xx)

條件2 若: 子-->根(倒樹) 則為 connect by 子 = prior 根

若 根--> 子(正樹) 則 connect 根 = prior 子

ORACLE樹形結構查詢

在oracle資料庫查詢中,我們經常會遇到對樹型結構表的查詢,這是個麻煩的問題。下面給大家介紹一種sql語句,實現遞迴查詢。語法如下 select 欄位1,欄位2,欄位3,from 表名 start with 條件1 connect by prior 條件2 where 條件3 下面舉乙個例子,有這...

Oracle查詢樹形結構

oracle中的select語句可以用start with.connect by prior子句實現遞迴查詢,connect by 是結構化查詢中用到的,其基本語法是 select from tablename start with cond1 connect by cond2 where cond...

oracle樹形結構查詢

最近用到了oracle的start with函式,所以在這裡簡單的記錄一下 首先可以造乙個表字段很簡單,如下 create table create table code id number,name varchar2 20 pid number tablespace tsdacns pctfree...