with查询(common table expressions)
目的:简化sql减少嵌套,可理解为在查询中定义了临时表,递归查询
with查询
postgres=# with test as (select generate_series(1,5)) select * from test;
generate_series
-----------------
1
2
3
4
5
(5 rows)

CTE递归查询
创建表并插入测试数据:表 funds 来存储基金和它们持有的子基金信息
假设我们有3个基金,其中基金2和基金3是基金1的子基金,基金3又持有基金2:
CREATE TABLE funds (
fund_id SERIAL PRIMARY KEY,
fund_name VARCHAR(255),
parent_fund_id INTEGER REFERENCES funds(fund_id)
);
INSERT INTO funds (fund_name, parent_fund_id) VALUES
('基金A', NULL), -- 基金A是顶级基金
('基金B', 1), -- 基金B是基金A的子基金
('基金C', 1); -- 基金C也是基金A的子基金
UPDATE funds SET parent_fund_id = 3 WHERE fund_id = 2;-- 基金C持有基金B
pos

最低0.47元/天 解锁文章
1941

被折叠的 条评论
为什么被折叠?



