我有一个类似于Translate SQLite query, with subquery, into Peewee statement和Can 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 中的一个或两个?
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以及为什么子查询具有别名?