将SQL子查询转换为Peewee ORM

时间:2015-11-24 18:30:20

标签: python sql peewee

我遇到与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?类似的问题。

我想要生成的结果是:给定一个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;

或者:

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

我怎么能Peewee-ify中的一个或两个?

1 个答案:

答案 0 :(得分:2)

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

merged_id

这很有效,但我不理解它所做的一切。 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) ))) 发生了什么,为什么子查询有别名?