zoukankan      html  css  js  c++  java
  • SQLite递归

    SQLite递归的用法的一些总结(by yellow3gold)

    1.新建表TestTable

    CREATE TABLE TestTable (
    "ID"  NVARCHAR2(20),
    "PARENTID"  NVARCHAR2(20),
    "NAME"  NVARCHAR(100),
    PRIMARY KEY ("ID")
    );

    2.插入测试数据

    INSERT INTO "TestTable" ("ID", "PARENTID", "NAME") VALUES (101, 1, 'name101');
    INSERT INTO "TestTable" ("ID", "PARENTID", "NAME") VALUES (102, 1, 'name102');
    INSERT INTO "TestTable" ("ID", "PARENTID", "NAME") VALUES (201, 2, 'name201');
    INSERT INTO "TestTable" ("ID", "PARENTID", "NAME") VALUES (301, 3, 'name301');
    INSERT INTO "TestTable" ("ID", "PARENTID", "NAME") VALUES (302, 3, 'name302');
    INSERT INTO "TestTable" ("ID", "PARENTID", "NAME") VALUES (303, 3, 'name303');
    INSERT INTO "TestTable" ("ID", "PARENTID", "NAME") VALUES (10101, 101, 'name10101');
    INSERT INTO "TestTable" ("ID", "PARENTID", "NAME") VALUES (30301, 303, 'name30301');
    INSERT INTO "TestTable" ("ID", "PARENTID", "NAME") VALUES (3010101, 30301, 'name3010101');
    INSERT INTO "TestTable" ("ID", "PARENTID", "NAME") VALUES (301010101, 3010101, 'name301010101');
    INSERT INTO "TestTable" ("ID", "PARENTID", "NAME") VALUES (1010101, 10101, 'name1010101');

    3.根据父ID(parentid)获取所有子ID

    WITH RECURSIVE
    GETID(N) AS (
    VALUES('3')
    UNION
    SELECT ID FROM TESTTABLE T, GETID WHERE T.PARENTID=GETID.N)
    SELECT ID ,PARENTID, NAME FROM TESTTABLE T WHERE T.PARENTID IN GETID

     4.根据ID获取所有父ID(parentid)

    WITH RECURSIVE
    GETID(N) AS (
    VALUES ('301010101')
    UNION 
    SELECT PARENTID FROM TESTTABLE T, GETID WHERE T.ID = GETID.N) 
    SELECT ID, PARENTID, NAME FROM TESTTABLE T WHERE T.ID IN GETID

    作者:九年新
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    Spring AOP概念理解 (通俗易懂)
    分享一下几个关于ssm及spring原理的专栏链接
    liux高级常用命令
    Linux基础常用命令
    SP1716 GSS3
    HDU6579 Operation
    CF1205C Palindromic Paths
    CF1213G Path Queries
    CF1213F Unstable String Sort
    CF1213E Two Small Strings
  • 原文地址:https://www.cnblogs.com/yellow3gold/p/15232765.html
Copyright © 2011-2022 走看看