python - Python - SQLAlchemy:group_by() 多列,带有 sum()
问题描述
我正在尝试制作 SQLAlchemy 等价物
select count(urlpair.id), urlpairlabel.label, sum(tag.relevant)
from urlpair
left join tag
on urlpair.id = tag.urlpair_id
join urlpairlabel
on urlpair.id = urlpairlabel.urlpair_id
group by urlpairlabel.label, urlpair.url_1;
但是与原始 SQL 相比,我尝试过的一些组合似乎过于缓慢
No errors; 45168 rows affected, taking 2.3 ms
与我的邮递员到 API
def get_pair_stats():
stats = db.session \
.query(
func.count(Urlpair.id),
Urlpairlabel.label,
func.sum(
case([(Tag.relevant == true(), 1)], else_=0))) \
.outerjoin(Tag) \
.join(Urlpairlabel) \
.group_by(Urlpairlabel.label, Urlpair.url_1) \
.all()
stats = [{
'count': count,
'label': label,
'positives': int(positives)
} for (count, label, positives) in stats]
return stats
结果:
Status: 200 OK Time: 6226 ms Size: 3.7 MB
我注意到当我不提供两个参数时,group_by
它似乎是 2s 而不是 6-8。有没有更好的方法来创建这个语句?