将 SQL 子查询转换为 Peewee ORM

kni*_*ite 2 python sql peewee

我有一个类似于Translate SQLite query, with subquery, into Peewee statementCan peewee nest SELECT 查询以便外部查询选择内部查询的聚合的问题?.

我试图生成的结果是:给定一个fruit包含 行的表格(type, variety, price),找到每种水果中最便宜的品种。http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/中描述了几种解决方案:

select f.type, f.variety, f.price
from (
   select type, min(price) as minprice
   from fruits group by type
) as x inner join fruits as f on f.type = x.type and f.price = x.minprice;
Run Code Online (Sandbox Code Playgroud)

或者:

select type, variety, price
from fruits
where price = (select min(price) from fruits as f where f.type = fruits.type);
Run Code Online (Sandbox Code Playgroud)

我如何才能 Peewee-ify 中的一个或两个?

kni*_*ite 5

http://charlesleifer.com/blog/techniques-for-querying-lists-of-objects-and-determining-the-top-related-item/抄袭,我有:

subquery = (Fruits
            .select(
                Fruits.type.alias('type'),
                fn.Min(Fruits.price).alias('min'))
            .group_by(Fruits.type)
            .alias('subquery'))

query = (Fruits
         .select()
         .join(subquery, on=(
             (Fruits.price == subquery.c.min) &
             (Fruits.type == subquery.c.type)
        )))
Run Code Online (Sandbox Code Playgroud)

这有效,但我不明白它在做什么。发生了什么subquery.c以及为什么子查询具有别名?

  • 给它取别名的原因是为了将它与查询中的其他 Fruits 实例区分开来。别名表示这是水果表的单独*实例*。“.c”约定允许您创建对相关子查询中的列等内容的引用。 (3认同)