gpt4 book ai didi

python - SQLAlchemy:在多对多关系中过滤运算符

转载 作者:太空宇宙 更新时间:2023-11-03 18:03:25 25 4
gpt4 key购买 nike

我有两个具有多对多关系的类,ItemsCategories

类别具有关联的值。

我想查询最高Categorie.value(如果有)小于给定值的所有Items

到目前为止,我已经尝试过这样的查询:

from sqlalchemy.sql import functions 
Session.query(Items).join(Categories,Items.categories).filter(functions.max(Categories.value)<3.14).all()

但在这种情况下,我收到 (OperationalError) 滥用聚合函数 max() 错误。

有办法进行这个查询吗?

最佳答案

您需要 GROUP BYHAVING 而不仅仅是 WHERE 来对聚合进行过滤。

Session.query(Items).join(Items.categories).group_by(Items.id).having(functions.max(Categories.value)<3.14).all()

编辑:要还包含没有任何类别的项目,我相信您可以进行外部联接并在 HAVING 子句中放置 OR :

Session.query(Items).outerjoin(Items.categories).group_by(Items.id)\
.having( (functions.max(Categories.value)<3.14) | (functions.count(Categories.id)==0) )\
.all()

关于python - SQLAlchemy:在多对多关系中过滤运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27326403/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com