如何在已连接的列上查询具有唯一值的行?

时间:2012-09-07 11:57:20

标签: python sqlalchemy

我正在尝试让我的popular_query子查询删除dupe Place.id,但它不会删除它。这是下面的代码。我尝试使用distinct但它不遵守order_by规则。

SimilarPost = aliased(Post)
SimilarPostOption = aliased(PostOption)
popular_query = (db.session.query(Post, func.count(SimilarPost.id)).
         join(Place, Place.id == Post.place_id).
         join(PostOption, PostOption.post_id == Post.id).
         outerjoin(SimilarPostOption, PostOption.val == SimilarPostOption.val).
         join(SimilarPost,SimilarPost.id == SimilarPostOption.post_id).
         filter(Place.id == Post.place_id).
         filter(self.radius_cond()).
         group_by(Post.id).
         group_by(Place.id).
         order_by(desc(func.count(SimilarPost.id))).
         order_by(desc(Post.timestamp))
         ).subquery().select()

all_posts = db.session.query(Post).select_from(filter.pick()).all()

我用

进行了测试打印输出
print [x.place.name for x in all_posts]

[u'placeB', u'placeB', u'placeB', u'placeC', u'placeC', u'placeA']

我该如何解决这个问题?

谢谢!

2 个答案:

答案 0 :(得分:4)

这可以让你得到你想要的东西:

SimilarPost = aliased(Post)
SimilarPostOption = aliased(PostOption)
post_popularity = (db.session.query(func.count(SimilarPost.id))
        .select_from(PostOption)
        .filter(PostOption.post_id == Post.id)
        .correlate(Post)
        .outerjoin(SimilarPostOption, PostOption.val == SimilarPostOption.val)
        .join(SimilarPost, sql.and_(
                SimilarPost.id == SimilarPostOption.post_id,
                SimilarPost.place_id == Post.place_id)
        )
        .as_scalar())
popular_post_id = (db.session.query(Post.id)
        .filter(Post.place_id == Place.id)
        .correlate(Place)
        .order_by(post_popularity.desc())
        .limit(1)
        .as_scalar())

deduped_posts = (db.session.query(Post, post_popularity)
        .join(Place)
        .filter(Post.id == popular_post_id)
        .order_by(post_popularity.desc(), Post.timestamp.desc())
        .all())

我不能说大型数据集的运行时性能,并且可能有更好的解决方案,但这是我设法从很多来源(MySQL JOIN with LIMIT 1 on joined tableSQLAlchemy - subquery in a WHERE clause合成的, SQLAlchemy Query documentation)。最大的复杂因素是你显然需要使用as_scalar将子查询嵌套在正确的位置,因此不能从同一子查询中返回Post id和count。

FWIW,这是一个庞然大物,我同意user1675804这个SQLAlchemy代码很难理解并且不易维护。您应该仔细研究任何可用的低技术解决方案,例如向数据库添加列或使用python代码执行更多工作。

答案 1 :(得分:1)

我不想听起来像这里的坏人但是......在我看来,你对这个问题的处理方法似乎远远不够理想......如果你使用postgresql,你可以用WITH简化整个事情。 ..但是一个更好的方法考虑到我的假设是这些帖子的读取次数会比更新更频繁,因为在表格中添加一些列,这些列由插入/更新到其他表的触发器更新,至少如果性能很可能永远成为一个问题,这是我的解决方案

不熟悉sqlalchemy,所以不能为你编写清晰的代码,但我能想出的唯一其他解决方案至少使用一个子查询来从order by中为每个列中的每个列选择通过,这将显着增加您已经很慢的查询

相关问题