Separate it separately:
WITH RECURSIVE t(n) AS (
A common table expression (CTE), which should include an initial query and a recursive query. CTE is called t and returns 1 column: n
Serial request:
SELECT 1
returns ans answer set (in this case only one line: 1) and places a copy of it in the final answer set
Now the recursive part begins:
UNION ALL
The rows returned from the seed query are now processed, and n + 1 is returned (again a set of answers from one row: 2) and is copied to the final set of answers:
SELECT n+1 FROM t WHERE n < 100
If this step returns a nonempty set of responses (activity_count> 0), it repeats (forever).
The WHERE clause for a computation such as n + 1 is usually used to avoid infinite recursion. Usually, as a rule, the maximum possible level based on data is known, and for complex queries it is too easy to establish some conditions, -)
Finally, a set of answers is returned:
) SELECT sum(n) FROM t;
When you just do SELECT * FROM t; , you will see all numbers from 1 to 100, this is not a very effective way to create this list.
The most important thing to remember is that each step creates a part of the final result, and only the next lines of the previous step are processed at the next recursion level.
source share