简体   繁体   English

从raw sql到flask-sqlalchemy

[英]from raw sql to flask-sqlalchemy

hello im trying to achieve this raw query with sqlalchemy: 你好我试图用sqlalchemy实现这个原始查询:

SELECT m.*, SUM(case when f.monkey = m.id then 1 else 0 end) as friends
FROM monkey as  m
LEFT JOIN friendship as f ON  m.id = f.monkey
GROUP BY m.id,  m.name
order by friends desc

so far i get the result i want with this raw query but i want to be able to .paginate them so i could keep working properly 到目前为止,我得到了我想要的结果这个原始查询,但我希望能够.paginate他们所以我可以继续正常工作

with my other queries what i did was this: 我的其他问题是我做的是这样的:

monkeys = models.Monkey.query.order_by(models.Monkey.name).paginate(page, 5, False)

fairly simple and i got what i wanted, i belive i have to do something like 相当简单,我得到了我想要的东西,我相信我必须做的事情

monkeys = models.Monkey.query.join(models.Friendship, db.func.count(models.Monkey.id == models.Friendship.monkey))

but im not getting what i want, i know im missing the sum() part but i tried with func.c.count()but i just dont know how to get it work, is it posible to achieve this in sqlalchemy? 但我没有得到我想要的,我知道我错过了sum()部分,但我尝试使用func.c.count(),但我只是不知道如何让它工作,是否可以在sqlalchemy实现这一点? im using postgres btw 即时通讯使用postgres btw

Looks like this will accomplish what you need 看起来这将实现您的需求

monkeys = models.Monkey.query.outerjoin(models.Friendship, db.func.count(models.Monkey.id == models.Friendship.monkey))

#or if you really want to stick to your above query

monkeys = models.Monkey.query.outerjoin(models.Friendship, db.func.SUM(func.IF(models.Monkey.id == models.Friendship.monkey, 1, 0)))

FYI I'm used to doing this in mysql, the func.* you call my be slightly different 仅供参考我习惯在mysql中执行此操作,func。*你称我的情况略有不同

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

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