gpt4 book ai didi

python - Peewee+sqlite 可以进行递归 CTE 查询吗?

转载 作者:太空宇宙 更新时间:2023-11-04 01:13:22 24 4
gpt4 key购买 nike

Peewee 是否可以执行以下 recursive CTE query

代码创建一个表示树结构的自引用表,查询查找一个元素的所有父元素。 (我是一个SQL初学者,欢迎任何改进建议)。

CREATE TABLE Parts ( 
Id INTEGER PRIMARY KEY,
Desc TEXT,
ParentId INTEGER
);

INSERT INTO Parts VALUES (1, 'CEO', NULL);
INSERT INTO Parts VALUES (2, 'VIP Sales', 1);
INSERT INTO Parts VALUES (3, 'VIP Operations', 1);
INSERT INTO Parts VALUES (4, 'Sales Manager Europe', 2);
INSERT INTO Parts VALUES (5, 'Sales Manager USA', 2);
INSERT INTO Parts VALUES (6, 'Sales Rep Europe 1', 4);
INSERT INTO Parts VALUES (7, 'Sales Rep Europe 2', 4);
INSERT INTO Parts VALUES (8, 'Sales Rep USA 1', 5);
INSERT INTO Parts VALUES (9, 'Sales Rep USA 2', 5);

WITH RECURSIVE Cte (
Level,
Id,
Desc,
ParentId,
ParentDesc
) AS (
SELECT 0,
Child.Id,
Child.Desc,
Parent.Id,
Parent.Desc
FROM Parts AS Child
JOIN Parts AS Parent ON Child.ParentId = Parent.Id
WHERE Child.Desc = 'Sales Rep USA 1'

UNION ALL

SELECT Cte.Level + 1,
Child.Id,
Child.Desc,
Parent.Id,
Parent.Desc
FROM Parts as Child, Cte
JOIN Parts AS Parent ON Child.ParentId = Parent.Id
WHERE Child.Id = Cte.ParentId
)
SELECT * FROM Cte;

最佳答案

Peewee 没有任何用于构造递归查询的内置工具。虽然可以使用一些 SQL 构建 block 类将其组合在一起,但老实说,将整个 SQL 查询传递给 peewee 的 raw() 方法可能会更好:

http://docs.peewee-orm.com/en/latest/peewee/api.html#Model.raw

关于python - Peewee+sqlite 可以进行递归 CTE 查询吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26283432/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com