【问题标题】:Postgres distinct on in sqlalchemy join: subquery must return only one columnPostgres distinct on sqlalchemy join:子查询必须只返回一列
【发布时间】: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


    【解决方案1】:

    试试这个

    comments_subquery = db.session.query(comments).distinct(comments.post_id, comments.text).subquery()
    
    query = db.session.query(posts, comments.text)\
            .outerjoin(comments_subquery, comments_subquery.c.post_id==posts.id)
            .filter(posts.timestamp >= start_date)
            .all()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-08
      • 2019-12-02
      • 1970-01-01
      • 1970-01-01
      • 2019-11-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多