我遇到与Translate SQLite query, with subquery, into Peewee statement和Can 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中的一个或两个?
答案 0 :(得分:2)
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)
)))
发生了什么,为什么子查询有别名?