我一直在努力解决将简单的SQL查询转换为SQLAlchemy表达式的问题,但我就是不能让事情像我在子查询中所说的那样。这是一个"Comments“表的单表查询;我想找出哪些用户发表了最多的第一条评论:
SELECT user_id, count(*) AS count
FROM comments c
where c.date = (SELECT MIN(c2.date)
FROM comments c2
WHERE c2.post_id = c.post_id
)
GROUP BY user_id
ORDER BY count DESC
LIMIT 20;我不知道如何写入子查询,以便它引用外部查询,如果我这样做了,我就不知道如何将其组装到外部查询本身中。(使用MySQL,这无关紧要。)
发布于 2020-12-02 20:25:05
嗯,在放弃了一段时间后,再回头看看,我想出了一些有用的东西。我相信有更好的办法,但是:
c2 = aliased(Comment)
firstdate = select([func.min(c2.date)]).\
where(c2.post_id == Comment.post_id).\
as_scalar() # or scalar_subquery(), in SQLA 1.4
users = session.query(
Comment.user_id, func.count('*').label('count')).\
filter(Comment.date == firstdate).\
group_by(Comment.user_id).\
order_by(desc('count')).\
limit(20)https://stackoverflow.com/questions/65097096
复制相似问题