【发布时间】:2022-01-01 07:06:51
【问题描述】:
我在这些帖子上有一张帖子表和一张 cmets 表。没有外键约束,但是评论上的 post_id 指的是帖子上的 id。
我正在使用这样的查询来获取最近的帖子列表,其中包含对该帖子的最新评论的文本:
SELECT posts.*, comments.text
FROM posts
LEFT JOIN (
SELECT DISTINCT ON ("post_id") *
FROM comments
ORDER BY "post_id", "timestamp" DESC
) comments ON posts.id=comments.post_id
WHERE posts.timestamp >= start_date;
我想将此查询转换为与 sqlalchemy 表达式一起使用。我试过这个:
query = select(posts, comments.c.text).\
join(comments, and_(select(comments).
distinct(comments.c.post_id).
order_by(comments.c.post_id, comments.c.timestamp.desc()),
posts.c.id == comments.c.post_id), isouter=True).\
where(posts.c.timestamp >= start_date)
但它创建的查询略有不同:
SELECT posts.id, posts.[other posts columns...], comments.text
FROM posts
LEFT OUTER JOIN comments ON (
SELECT DISTINCT ON (comments.post_id) comments.text, comments.[other comments columns...]
FROM comments
ORDER BY comments.post_id, comments.timestamp DESC
) AND posts.id = comments.post_id
WHERE posts.timestamp >= start_date;
导致错误:sqlalchemy.exc.ProgrammingError: (psycopg2.errors.SyntaxError) subquery must return only one column
【问题讨论】:
标签: postgresql sqlalchemy