【问题标题】:SQLAlchemy: how to join tables and filter by != condition?SQLAlchemy:如何连接表并按!=条件过滤?
【发布时间】:2018-08-15 02:10:53
【问题描述】:

SQLAlchemy for MySQL 没有外键,我创建了这些表:

USER TABLE:
user_id
user_name

BLOCK TABLE:
user_id
blocked_user_id

POST TABLE:
post_id
post_user_id
post_content

COMMENT TABLE:
comment_id
comment_user_id
comment_content
post_id
post_user_id

我想选择帖子的 cmets 和 COMMENT.comment_user_id 不在 BLOCK.blocked_user_id 中,我试过这个,但结果为空:

comments = COMMENT.query.outerjoin(BLOCK, BLOCK.blocked_user_id == COMMENT.comment_user_id).filter(COMMENT.post_id == postid, COMMENT.post_user_id != current_user.user_id).all()

作为替代解决方案,我必须使用两个查询步骤,第一步选择所有被阻止的用户,第二步选择帖子的 cmets 过滤器

COMMENT.comment_user_id.notin_(blocked_users)

【问题讨论】:

    标签: python mysql sqlalchemy flask-sqlalchemy


    【解决方案1】:

    假设您可以在下面的查询中使用 session 进行 sqlalchemy,当您对评论和块表进行左连接时,将返回正确的结果

    comments = session.query(COMMENT).outerjoin(BLOCK, COMMENT.user_id == BLOCK.user_id).filter(BLOCK.user_id == None).all()
    

    所以您的原始查询将得到如下所示的内容

    comments = COMMENT.query.outerjoin(BLOCK, COMMENT.blocked_user_id == BLOCK.comment_user_id).filter(BLOCK.blocked_user_id==None).all()
    

    注意:上面的查询只过滤所有没有被阻塞表的用户 ID 的 cmets,您可以根据您对其他列的要求添加更多过滤条件

    【讨论】:

      猜你喜欢
      • 2019-12-26
      • 2018-10-15
      • 2018-02-18
      • 2014-09-07
      • 1970-01-01
      • 2021-06-25
      • 2013-01-19
      • 1970-01-01
      • 2011-06-05
      相关资源
      最近更新 更多