basic recursive query on sqlite3?

后端 未结 5 1925
猫巷女王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:26

    This is the most basic query that I could think of, it generates a series where we start with 1,2 and keep adding 1 till we hit 20. not much useful but playing around a bit with this will help you build more complex recursive ones

    The most basic series

    WITH b(x,y) AS 
    (
        SELECT 1,2 
        UNION ALL 
        SELECT x+ 1, y + 1 
        FROM b 
        WHERE x < 20
    ) SELECT * FROM b;
    

    Prints

    1|2
    2|3
    3|4
    4|5
    5|6
    6|7
    7|8
    8|9
    9|10
    10|11
    11|12
    12|13
    13|14
    14|15
    15|16
    16|17
    17|18
    18|19
    19|20
    20|21
    

    Here is another simple example that generates Fibonacci numbers we start with a = 0, b = 1 and then go a = b, b = a + b just like you would do in any programming language

    Fibonacci Series

    WITH b(x,y) AS 
    (
        SELECT 0,1 
        UNION ALL 
        SELECT y, x + y 
        FROM b 
        WHERE x < 10000
    ) select * FROM b;
    

    Prints

    0|1
    1|1
    1|2
    2|3
    3|5
    5|8
    8|13
    13|21
    21|34
    34|55
    55|89
    89|144
    144|233
    233|377
    377|610
    610|987
    987|1597
    1597|2584
    2584|4181
    4181|6765
    6765|10946
    10946|17711
    

提交回复
热议问题