basic recursive query on sqlite3?

后端 未结 5 1934
猫巷女王i
猫巷女王i 2020-11-27 16:49

I have a simple sqlite3 table that looks like this:

Table: Part
Part    SuperPart
wk0Z    wk00
wk06    wk02
wk07    wk02
eZ01    eZ00
eZ02    eZ00
eZ03    eZ         


        
5条回答
  •  青春惊慌失措
    2020-11-27 17:44

    Based on the samples found in sqlite with documentation, the query

    DROP TABLE IF EXISTS parts;
    CREATE TABLE parts (part, superpart);
    INSERT INTO parts VALUES("wk0Z", "wk00");
    INSERT INTO parts VALUES("wk06", "wk02");
    INSERT INTO parts VALUES("wk07", "wk02");
    INSERT INTO parts VALUES("eZ01", "eZ00");
    INSERT INTO parts VALUES("eZ02", "eZ00");
    INSERT INTO parts VALUES("eZ03", "eZ01");
    INSERT INTO parts VALUES("eZ04", "eZ01");
    
    WITH RECURSIVE
      under_part(parent,part,level) AS (
         VALUES('?', 'eZ00', 0)
         UNION ALL
         SELECT parts.superpart, parts.part, under_part.level+1 
            FROM parts, under_part
         WHERE parts.superpart=under_part.part
      )
      SELECT SUBSTR('..........',1,level*3) || "(" || parent || ", " || part || ")" FROM under_part
      ;
    

    would output

      (?, eZ00)
      ...(eZ00, eZ01)
      ...(eZ00, eZ02)
      ......(eZ01, eZ03)
      ......(eZ01, eZ04)
    

    as "it should be" expected

    the initial record of the recursive table can be replaced with

    VALUES ((SELECT superpart FROM parts WHERE part='eZ00'), 'eZ00', 0)
    

    in order to get also the parent of the initial superpart, although in this case there is no parent at all.

提交回复
热议问题