3

我正在尝试选择按最新回复时间降序排列的最新线程(线程)(回复是帖子模型,这是标准论坛查询)。在 SQL 中,我会这样写:

SELECT * FROM thread AS t ORDER BY (SELECT MAX(posted_at) FROM post WHERE thread_id = t.id) DESC

我如何在 SQLAlchemy 中做这样的事情?我试过这样的事情:

scalar = db.select[func.max(Post.posted_at)].where(Post.thread_id == Thread.id).as_scalar()
threads = Thread.query.order_by(scalar.desc()).all()

但似乎我不明白标量是如何工作的。第五次阅读文档无济于事。有人可以帮我在 SQLAlchemy 中编写这样的查询吗?我在这个应用程序中使用了 flask-sqlalchemy 和 MySQL。

4

1 回答 1

4

对我来说看起来不错,这是一个测试:

from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Thread(Base):
    __tablename__ = 'thread'

    id = Column(Integer, primary_key=True)


class Post(Base):
    __tablename__ = 'post'

    id = Column(Integer, primary_key=True)
    thread_id = Column(Integer, ForeignKey('thread.id'))
    posted_at = Column(String)

s = Session()

scalar = select([func.max(Post.posted_at)]).where(Post.thread_id == Thread.id).as_scalar()

q = s.query(Thread).order_by(scalar.desc())

print q

输出(注意我们只是在这里打印 SQL):

SELECT thread.id AS thread_id 
FROM thread ORDER BY (SELECT max(post.posted_at) AS max_1 
FROM post 
WHERE post.thread_id = thread.id) DESC

看起来很像您的查询

于 2013-07-08T04:42:30.130 回答