简体   繁体   English

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

[英]SqlAlchemy: How to use the result of a selected subquery inside the where clause

I wish to get a list of articles along with the count of the comments for each article我希望获得文章列表以及每篇文章的评论数

My query looks like this -我的查询看起来像这样 -

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)

it gives this error它给出了这个错误

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

How can I use the count which I selected to filter the result?如何使用我选择的计数来过滤结果?

Using the Query.subquery() method.使用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)
)

This works, but is it the most optimal query?这有效,但它是最佳查询吗?

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

query = query.add_column(count_subq.c.comment_count.label("comment_count"))

query = query.outerjoin((count_subq, count_subq.c.article_id==Article.id))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM