python - 如何将此查询转换为 Peewee ORM?

标签 python mysql join orm peewee

我正在使用(优秀)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/

相关文章:

python - 从 python 打开一个终端

mysql - 如何在同一个表中查找相对于另一列的列?

mysql - 为什么我们在多个删除中的 'DELETE' 之后提供别名

hadoop - 如何在mapreduce中加入多个数据集

python - 如何消除由于 scipy/numpy fft 中的零填充而产生的边界效应?

python - python如何在赋值运算符后赋值

python - 如何使用 Pyvmomi 创建带有附加 vmdk 磁盘的虚拟机(非克隆)?

mysql - 使用参数将数据插入 MySQLTable

php - MySQL 按文本排序

mysql - 合并两个 MySQL 表