1

我的 oracle 数据库中有一个表,如下所示:

FolderID    Name    ParentFolderID
1200        A       1000
1201        B       1000
1202        C       1000
1203        D       1000
1204        E       1200
1205        F       1200
1206        G       1201
1207        H       1205
1208        I       1205
1209        J       1205

在此表中,文件夹 id 1000 有孩子 1200、1201、1202、1203。文件夹 id 1200 有孩子 1204、1205。1201 有孩子 1206。而 1205 有孩子 1207、1208 和 1209。我要找的是得到我传递给查询的文件夹 ID 的所有子文件夹 ID。如果我通过 1000,它应该返回所有子行和子子行。

谢谢

4

3 回答 3

3
select folderid, name
from the_unknown_table
start with folderid = 1000
connect by prior folderid = parentfolderId;
于 2012-05-17T10:50:40.247 回答
2

尝试CONNECT BY查询,例如;

SELECT 
folderid, 
name
FROM the_unknown_table
START WITH  folderid = :first_folder_id
CONNECT BY PRIOR folderid = parentfolderId;

如果你想在一列中用逗号分隔所有内容SYS_CONNECT_BY_PATH

SELECT 
folderid, 
SYS_CONNECT_BY_PATH(folderid,',') my_path,
name
FROM the_unknown_table
START WITH  folderid = :first_folder_id
CONNECT BY PRIOR folderid = parentfolderId;
于 2012-05-17T10:55:20.837 回答
0

标准 SQL 方式(相当于 connect by/prior)使用递归 CTE:

DROP SCHEMA opa CASCADE;
CREATE SCHEMA opa;

SET search_path='opa';

CREATE TABLE parents
    ( id    INTEGER NOT NULL PRIMARY KEY 
    , zname text
    , parent_id INTEGER REFERENCES parents (id)
    );  
INSERT INTO parents(id,zname,parent_id) VALUES
(1000        , '@',       NULL)
,(1200        , 'A',       1000)
,(1201        , 'B',       1000)
,(1202        , 'C',       1000)
,(1203        , 'D',       1000)
,(1204        , 'E',       1200)
,(1205        , 'F',       1200)
,(1206        , 'G',       1201)
,(1207        , 'H',       1205)
,(1208        , 'I',       1205)
,(1209        , 'J',       1205)
    ;   

WITH RECURSIVE zopa AS (
    SELECT p0.id AS opa_id, p0.id AS id
      , p0.zname AS zname, p0.parent_id  AS parent_id
    FROM  parents p0
    WHERE NOT EXISTS (
        SELECT * FROM parents nx WHERE nx.id = p0.parent_id)
    UNION
    SELECT 
        zp.opa_id AS opa_id
        , p1.id AS id
        , p1.zname AS zname
        , p1.parent_id AS parent_id
    FROM parents p1
    JOIN zopa zp ON zp.id = p1.parent_id
    )   
select *
FROM zopa ct
WHERE ct.opa_id = 1000
    ;   

结果:

NOTICE:  drop cascades to table opa.parents
DROP SCHEMA
CREATE SCHEMA
SET
NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index "parents_pkey" for table "parents"
CREATE TABLE
INSERT 0 11
 opa_id |  id  | zname | parent_id 
--------+------+-------+-----------
   1000 | 1000 | @     |          
   1000 | 1202 | C     |      1000
   1000 | 1200 | A     |      1000
   1000 | 1201 | B     |      1000
   1000 | 1203 | D     |      1000
   1000 | 1205 | F     |      1200
   1000 | 1204 | E     |      1200
   1000 | 1206 | G     |      1201
   1000 | 1209 | J     |      1205
   1000 | 1207 | H     |      1205
   1000 | 1208 | I     |      1205
(11 rows)
于 2012-05-17T11:09:11.210 回答