【问题标题】:Translating SQL sub-query to Peewee ORM将 SQL 子查询转换为 Peewee ORM
【发布时间】:2015-11-25 03:41:53
【问题描述】:

我有一个类似于Translate SQLite query, with subquery, into Peewee statementCan peewee nest SELECT queries such that the outer query selects on an aggregate of the inner query? 的问题。

我试图生成的结果是:给定一个包含(type, variety, price) 行的fruit 表,找出每种水果中最便宜的品种。 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;

或者:

select type, variety, price
from fruits
where price = (select min(price) from fruits as f where f.type = fruits.type);

我如何对其中一个或两个进行 Peewee-ify?

【问题讨论】:

    标签: python sql peewee


    【解决方案1】:

    抄袭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)
            )))
    

    这行得通,但我不明白它在做什么。 subquery.c 是怎么回事,为什么子查询有别名?

    【讨论】:

    • 给它取别名的原因是为了将它与查询中的其他 Fruits 实例区分开来。别名表示这是 fruits 表的一个单独的 instance。 “.c”约定允许您创建对相关子查询中列等内容的引用。
    • 也许我在docs 中忽略了这一点,但这样的例子肯定应该列在那里。很高兴我找到了这个答案。
    猜你喜欢
    • 1970-01-01
    • 2018-06-10
    • 2016-04-20
    • 2020-09-12
    • 1970-01-01
    • 1970-01-01
    • 2019-10-17
    • 2021-07-06
    相关资源
    最近更新 更多