我正在使用(优秀)Peewee ORM为了满足我在 Python 中的查询需求,我现在想要转换以下查询:
select t1.created, t1.property_id, t1.requesting_user_id, t1.type, t1.response
from pdr t1
inner join (
select max(id) as id, property_id, requesting_user_id
from pdr
where property_id = 7
group by requesting_user_id
) as t2 on t2.id = t1.id
所以我想出了以下内容:
PDR.select()\
.join(PDR)\
.where(PDR.property == 7)\
.group_by(PDR.requesting_user)
但这会创建以下 sql:
SELECT t1.id, t1.created, t1.property_id, t1.requesting_user_id, t1.type, t1.comment, t1.responding_user_id, t1.property_details_request_id, t1.response
FROM pdr AS t1
INNER JOIN pdr AS t1
ON (t1.property_details_request_id = t1.id)
WHERE (t1.property_id = 7)
GROUP BY t1.requesting_user_id
我尝试了其他几种变体,但我有点卡住了。
有人知道如何将我的查询转换为 Peewee 吗?欢迎所有提示!
最佳答案
尝试以下操作(未经测试,但希望有帮助):
PDRAlias = PDR.alias()
subq = (PDRAlias
.select(fn.MAX(PDRAlias.id).alias('max_id'), PDRAlias.property, PDRAlias.requesting_user)
.where(PDRAlias.property == 7)
.group_by(PDRAlias.requesting_user)
.alias('subq'))
query = (PDR
.select()
.join(subq, on=(subq.c.max_id == PDR.id)))
关于python - 如何将此查询转换为 Peewee ORM?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29428917/