简体   繁体   English

Select 来自 peewee 的查询

[英]Select from a query with peewee

I have some troubles implementing the following query with peewee:我在使用 peewee 实现以下查询时遇到了一些麻烦:

SELECT *
FROM (
    SELECT datas.*, (rank() over(partition by tracking_id order by date_of_data DESC)) as rank_result
    FROM datas
    WHERE tracking_id in (1, 2, 3, 4, 5, 6)
)
WHERE rank_result < 3;

I have tried to do the following:我尝试执行以下操作:

subquery = (Datas.select(Datas.tracking, Datas.value, Datas.date_of_data,
                                 fn.rank().over(partition_by=[Datas.tracking],
                                                order_by=[Datas.date_of_data.desc()]).alias('rank'))
                    .where(Datas.tracking.in_([1, 2, 3, 4, 5, 6])))
result = (Datas.select()
               .from_(subquery)
               .where(SQL('rank') < 3))

but since I'm doing "Model.select()" i'm getting all the fields in the SQL SELECT which i don't want and which doesn't make my query work.但由于我正在执行“Model.select()”,所以我得到了 SQL SELECT 中的所有字段,我不想要这些字段,这不会使我的查询工作。 Here is the schema of my table:这是我的表的架构:

CREATE TABLE IF NOT EXISTS "datas" 
(
    "id" INTEGER NOT NULL PRIMARY KEY, 
    "tracking_id" INTEGER NOT NULL, 
    "value" INTEGER NOT NULL, 
    "date_of_data" DATETIME NOT NULL, 
    FOREIGN KEY ("tracking_id") REFERENCES "follower" ("id")
);
CREATE INDEX "datas_tracking_id" ON "datas" ("tracking_id");

Thanks!谢谢!

You probably want to use the .select_from() method on the subquery:您可能想在子查询上使用.select_from()方法:

subq = (Datas.select(Datas.tracking, Datas.value, Datas.date_of_data,
                     fn.rank().over(partition_by=[Datas.tracking],
                                    order_by=[Datas.date_of_data.desc()]).alias('rank'))
                    .where(Datas.tracking.in_([1, 2, 3, 4, 5, 6])))

result = subq.select_from(
    subq.c.tracking, subq.c.value, subq.c.date_of_data,
    subq.c.rank).where(subq.c.rank < 3)

Produces:产生:

SELECT "t1"."tracking", "t1"."value", "t1"."date_of_data", "t1"."rank" 
FROM (
    SELECT "t2"."tracking", 
           "t2"."value", 
           "t2"."date_of_data", 
           rank() OVER (
              PARTITION BY "t2"."tracking" 
              ORDER BY "t2"."date_of_data" DESC) AS "rank" 
    FROM "datas" AS "t2" 
    WHERE ("t2"."tracking" IN (?, ?, ?, ?, ?, ?))) AS "t1" 
WHERE ("t1"."rank" < ?)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM