如何使用sql查询行数据和父路径字符串?

时间:2014-11-10 02:48:11

标签: sql oracle11g

数据库版本:Oracle 11g
我的数据库表创建了secript:

CREATE TABLE test(
  id INTEGER PRIMARY KEY,
  parentId INTEGER,
  name VARCHAR(50)
);

INSERT INTO test (id, parentId, name) VALUES (1, 0, 'A');
INSERT INTO test (id, parentId, name) VALUES (2, 1, 'B');
INSERT INTO test (id, parentId, name) VALUES (3, 1, 'C');
INSERT INTO test (id, parentId, name) VALUES (4, 2, 'D');
INSERT INTO test (id, parentId, name) VALUES (5, 4, 'E');

现在,如何使用sql查询,如下结果:

enter image description here

提前感谢!

2 个答案:

答案 0 :(得分:1)

此查询将为您完成:

SELECT
t1.id, t1.parentId, t1.name, 
  CONCAT(
    IF (t5.name IS NOT NULL, CONCAT(t5.name, '->'), ''),
    IF (t4.name IS NOT NULL, CONCAT(t4.name, '->'), ''),     
    IF (t3.name IS NOT NULL, CONCAT(t3.name, '->'), ''),
    IF (t2.name IS NOT NULL, CONCAT(t2.name, '->'), ''),
    t1.name) AS parent_path
FROM
test t1
LEFT JOIN test t2 ON t2.id = t1.parentId
LEFT JOIN test t3 ON t3.id = t2.parentId
LEFT JOIN test t4 ON t4.id = t3.parentId
LEFT JOIN test t5 ON t5.id = t4.parentId

你只需要通过潜在的父母来解决问题。这只会深入4级,所以如果你需要更多,你必须添加额外的左连接。你也可以在这个小提琴中看到这个:

http://sqlfiddle.com/#!2/342fa/5

答案 1 :(得分:1)

请参阅此处的小提琴:http://sqlfiddle.com/#!4/342fa0/25

这适用于ORACLE 11g

SELECT
    t1.id, t1.parentId, t1.name,
  CONCAT ( DECODE (t5.name, NULL, '',  CONCAT(t5.name, '->')),
  CONCAT ( DECODE (t4.name, NULL, '',  CONCAT(t4.name, '->')),
  CONCAT ( DECODE (t3.name, NULL, '',  CONCAT(t3.name, '->')),
  CONCAT ( DECODE (t2.name, NULL, '',  CONCAT(t2.name, '->')),
   T1.NAME   ) )))   
   AS parent_path

FROM
test t1
LEFT JOIN test t2 ON t2.id = t1.parentId
LEFT JOIN test t3 ON t3.id = t2.parentId
LEFT JOIN test t4 ON t4.id = t3.parentId
LEFT JOIN test t5 ON t5.id = t4.parentId
ORDER BY ID