postgresql with recursive

Note
Strictly speaking, this process is iteration not recursion, but RECURSIVE is the terminology chosen by the SQL standards committee.

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

  1. 首先把第一个查询里面的内容(……where part = ‘our_product’)赋值给中间表里临时工作表included_parts三个列(sub_part, part, quantity), 作为初始值。下面接把该表看作一个临时工作表included_parts,对于union就对所有的重复的行进行清除仅保留一行,union all则不会。。
  2. 只要临时工作表included_parts不为空,进行下一步,否则查询结束。
  3. 临时工作表included_partsparts表结合查询,得到的结果放到一个中间表,对于union就对所有的重复的行进行清除仅保留一行,union all则不会。
  4. 中间表的内容赋给临时工作表included_parts,对于union就对所有的重复的行进行清除仅保留一行,union all则不会。清空中间表节约内存。
  5. 进行第二步。
  6. 结束?官网的说明感觉很绕口,也没说怎么保存所有输出,但是差一下肯定有**其他表(例如:included_parts)**来保存所有输出的呗,把每个步骤的结果都插入到一个最终表里,变成你所看到的输出~

官网:https://www.postgresql.org/docs/current/queries-with.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值