python - SqlAlchemy:如何在 where 子句中使用选定子查询的结果

标签 python sql sqlalchemy

我希望获得文章列表以及每篇文章的评论数

我的查询是这样的-

comments_subq = meta.Session.query(func.count(Comment.id)).filter(Comment.article_id==Article.id).as_scalar()

articles = meta.Session.query(Article, comments_subq.label("comment_count"))

articles = articles.filter(column('comment_count') >= 5)

它给出了这个错误

column "comment_count" does not exist LINE 5: WHERE comment_count >= 5

如何使用我选择的计数来过滤结果?

最佳答案

使用 Query.subquery()方法。

comments_subq = (
    meta.Session.query(
        Comment.article_id,
        func.count(Comment.id).label("comment_count")
    )
    .group_by(Comment.article_id)
    .subquery()
)

articles = (
    meta.Session.query(
        Article, 
        comments_subq.c.comment_count
    )
    .outerjoin(comments_subq, Article.id == comments_subq.c.article_id)
    .filter(comments_subq.c.comment_count >= 5)
)

关于python - SqlAlchemy:如何在 where 子句中使用选定子查询的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16601470/

相关文章:

python - tensorflow 基本word2vec示例: Shouldn't we be using weights [nce_weight Transpose] for the representation and not embedding matrix?

python - 在 Tensorflow 中使用 TPU 时,是否有适当的解决方法来保存本地驱动器中的检查点?

mysql - SQL strip 最长公共(public)前缀

mysql - 子查询引用外部列的问题

sql - 获取用户的最新记录

Python SQL 查询字符串格式化

python - 为 pyenv + virtualenv 生成 python3-config

mysql - 如何过滤掉特定的电子邮件地址?

python - join后使用filter_by

python - SQLAlchemy 事件不工作