29. 再帰ビュー
yohgaki@127 ~=# CREATE VIEW fib_up_to_50 AS
WITH RECURSIVE
fib AS (
SELECT 0 AS a, 1 AS b
UNION ALL
SELECT b, a + b FROM fib WHERE b <= 50
)
SELECT a FROM fib;
CREATE VIEW
yohgaki@127 ~=# SELECT * FROM fib_up_to_50;
a
----
0
1
1
2
3
5
8
13
21
34
2013/8/3中国DB勉強会 29
30. WITH RECURSIVEのみでも可能
yohgaki@127 ~=# WITH RECURSIVE
fib AS (
SELECT 0 AS a, 1 AS b
UNION ALL
SELECT b, a + b FROM fib WHERE b <= 50
)
SELECT a FROM fib;
a
----
0
1
1
2
3
5
8
13
21
34
2013/8/3中国DB勉強会 30
31. 実用的な例
WITH RECURSIVE included_parts(sub_part, part, quantity) AS (
SELECT sub_part, part, quantity FROM parts WHERE part = 'our_product'
UNION ALL
SELECT p.sub_part, p.part, p.quantity
FROM included_parts pr, parts p
WHERE p.part = pr.sub_part
)
SELECT sub_part, SUM(quantity) as total_quantity
FROM included_parts
GROUP BY sub_part
2013/8/3中国DB勉強会 31