oracle和postgresql 递归查询父子关系记录语法区别

Posted 长东

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了oracle和postgresql 递归查询父子关系记录语法区别相关的知识,希望对你有一定的参考价值。

oracle:

一、数据

db数据字段如下:

task_id             task_name         t.parent_task_id       ***
***                     ***                          ***                               ***
000001            t1                         ***                                 ***
000002            t11                       000001                        ***
000005            t12                       000001                         ***
000003            t111                    000002                         ***
000004            t1111                  000003                         ***
000006            t121                    000005                         ***
000007            t1211                  000006                         ***
***                     ***                       ***                                 ***

二、格式
        Select * from …. Where [结果过滤条件语句]
  Start with  [and起始条件过滤语句]
  Connect by prior [and中间记录过滤条件语句]
三、查找所有下级
        select * from tablename start with id=1 connect by prior id=pid
  注意:此sql能查找id=1的数据的所有下级,写sql语句时要注意,因为是从id开始查找下级,所以connect by prior 子句的条件是         id=pid
四、查找所有上级
       select * from tablename start with id=5 connect by prior pid=id
  因为是从id开始查找上级,所以connect by prior 子句的条件是pid=d

select t.task_id ,t.task_name ,t.parent_task_id 
from t_task t 
start with task_id=000001
connect by prior task_id = parent_task_id;

五、显示结果

结果显示:

task_id                 task_name          t.parent_task_id
000001                t1          
000002                t11                       000001
000003                t111                     000002
000004                t1111                    000003
000005                t12                       000001
000006                t121                     000005
000007                t1211                   000006

postgresql:

查询父节点下所有的子节点

WITH recursive fileinfo
 (pk_fi_id,
  f_fi_parentid)
AS
(
SELECT
        pk_fi_id ,
        f_fi_parentid 
    FROM
        t_fileinfo
    WHERE
        pk_fi_id = 92719f78-22d6-4db1-a484-dff34de76890
UNION ALL
SELECT
            mm.pk_fi_id ,
            mm.f_fi_parentid 
        FROM
            t_fileinfo AS mm
INNER JOIN fileinfo AS child ON mm.f_fi_parentid = child.pk_fi_id
)
SELECT
  *
FROM fileinfo

 










以上是关于oracle和postgresql 递归查询父子关系记录语法区别的主要内容,如果未能解决你的问题,请参考以下文章

SQL递归查询所有子节点

PostGIS 递归方法

用于获取存储在单个表中的 n 级父子关系的 Postgresql 查询

java 找到一节点的所有子节点 是否得递归实现?

PostgreSQL父子建表查询所有的子数据-利用自定义函数查询

PostgreSQL父子建表查询所有的子数据-利用自定义函数查询