存储数据关系的时,表结构关系会存在一种树形关系,比如通过一个parentId字段来关联,下面用一个简单的小例子来描述Oracle中的递归查询

  • 创建表
CREATE TABLE COMMENTS (COMMENTID INTEGER, PARENTID INTEGER, ARTICLEID INTEGER, COMMENTBODY VARCHAR2(500));
  • 插入初始化数据
INSERT INTO COMMENTS (COMMENTID, PARENTID, ARTICLEID, COMMENTBODY) VALUES (1, null, 1, '第一条评论');
INSERT INTO COMMENTS (COMMENTID, PARENTID, ARTICLEID, COMMENTBODY) VALUES (2, 1, 1, '第一条评论的第一条回复');
INSERT INTO COMMENTS (COMMENTID, PARENTID, ARTICLEID, COMMENTBODY) VALUES (3, 2, 1, '第一条评论的第一条回复的第一条回复');
INSERT INTO COMMENTS (COMMENTID, PARENTID, ARTICLEID, COMMENTBODY) VALUES (4, 2, 1, '第一条评论的第一条回复的第二条回复');
INSERT INTO COMMENTS (COMMENTID, PARENTID, ARTICLEID, COMMENTBODY) VALUES (5, 1, 1, '第一条评论的第二条回复');
  • 递归查询样例

    • 通过根节点遍历子节点(包含根节点)

      select * from COMMENTS start with COMMENTID=1 connect by prior COMMENTID=PARENTID
      
    • 通过根节点遍历子节点(不包含根节点)

      select * from COMMENTS start with PARENTID=1 connect by prior COMMENTID=PARENTID
      
    • 通过子节点向根节点追朔

      select * from COMMENTS start with COMMENTID=4 connect by prior PARENTID=COMMENTID
      
    • 可通过level 关键字查询所在层次

      select t.*,level from COMMENTS t start with PARENTID=1 connect by prior COMMENTID=PARENTID
      
  • 总结

    • start with...connect by: start with 后面所跟的是递归的种子节点(开始节点)
    • connect by prior: 如果缺省prior,则只能查询到符合条件的起始行,并不进行递归查询;后面所放的字段是有依赖关系的,它指明了查询的方向

参考: https://www.cnblogs.com/henuyuxiang/p/6155952.html