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

时间:2014-10-09 16:25:40

标签: python sqlite peewee

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;

1 个答案:

答案 0 :(得分:2)

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

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

相关问题