Oracle的递归公共表表达式

 查询节点id为2的所有子节点的数据,包括向下级联

WITH T1 (id, parent_id, data) AS (
  SELECT id, parent_id, data
  FROM nodes
  WHERE id = 2
  UNION ALL
  SELECT t.id, t.parent_id, t.data
  FROM nodes t
  JOIN T1 n ON t.parent_id = n.id
)
SELECT * FROM T1;

Oracle的递归公共表表达式_第1张图片

--建表语句 

CREATE TABLE nodes (
  id NUMBER,
  parent_id NUMBER,
  data varchar2(100)
);

--插入数据 

INSERT INTO nodes (id, parent_id, data) VALUES (1, NULL, 'Node 1');
INSERT INTO nodes (id, parent_id, data) VALUES (2, 1, 'Node 2');
INSERT INTO nodes (id, parent_id, data) VALUES (3, 1, 'Node 3');
INSERT INTO nodes (id, parent_id, data) VALUES (4, 2, 'Node 4');
INSERT INTO nodes (id, parent_id, data) VALUES (5, 2, 'Node 5');
INSERT INTO nodes (id, parent_id, data) VALUES (6, 3, 'Node 6');
INSERT INTO nodes (id, parent_id, data) VALUES (7, 3, 'Node 7');
INSERT INTO nodes (id, parent_id, data) VALUES (8, 4, 'Node 8');
INSERT INTO nodes (id, parent_id, data) VALUES (9, 4, 'Node 9');
INSERT INTO nodes (id, parent_id, data) VALUES (10, 5, 'Node 10');
INSERT INTO nodes (id, parent_id, data) VALUES (11, 5, 'Node 11');
INSERT INTO nodes (id, parent_id, data) VALUES (12, 6, 'Node 12');
INSERT INTO nodes (id, parent_id, data) VALUES (13, 6, 'Node 13');
INSERT INTO nodes (id, parent_id, data) VALUES (14, 7, 'Node 14');
INSERT INTO nodes (id, parent_id, data) VALUES (15, 7, 'Node 15');

你可能感兴趣的:(oracle,sql,数据库)