【问题标题】:Can Peewee+sqlite make a recursive CTE query?Peewee+sqlite 可以做递归 CTE 查询吗?
【发布时间】:2014-10-10 21:59:13
【问题描述】:

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;

【问题讨论】:

    标签: python sqlite peewee


    【解决方案1】:

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

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-25
    • 1970-01-01
    • 2016-09-28
    • 1970-01-01
    相关资源
    最近更新 更多