![](/img/trans.png)
[英]How, in python, can I count unique values in a column for gradually increasing numbers of rows within groups
[英]How can I query rows with unique values on a joined column?
我试图让我的Popular_query子查询删除重复的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']
我怎样才能解决这个问题?
谢谢!
这应该给您您想要的:
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,连接表上的LIMIT 1 , SQLAlchemy-WHERE中的子查询)进行了综合子句 , SQLAlchemy查询文档 )。 最大的复杂因素是您显然需要使用as_scalar
将子查询嵌套在正确的位置,因此无法从同一子查询返回Post ID和计数。
FWIW,这有点像庞然大物,我同意user1675804的观点,认为如此深的SQLAlchemy代码很难理解,而且很难维护。 您应该仔细查看任何其他低技术含量的解决方案,例如向db添加列或使用python代码完成更多工作。
我不想在这里听起来像个坏人,但是...我认为您对问题的处理似乎远未达到最佳效果...如果您使用的是Postgresql,则可以使用WITH简化整个过程...但是根据我的假设,一种更好的方法是,我认为这些帖子的阅读频率将比更新的阅读频率高得多,这是向您的表中添加一些列,这些列由插入/更新到其他表上的触发器来更新,至少在性能可能变为问题,这是我会去的解决方案
对sqlalchemy不太熟悉,因此无法为您编写清晰的代码,但是我能想到的唯一其他解决方案是至少使用一个子查询为group by中的每个列从order by中选择事物,并且这将大大增加您已经很慢的查询
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.