简体   繁体   English

SQLAlchemy:如何联接表并按!=条件进行过滤?

[英]SQLAlchemy: how to join tables and filter by != condition?

SQLAlchemy for MySQL without foreign key, I've created these tables: 没有外键的MySQL的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

I want to select post's comments and COMMENT.comment_user_id not in BLOCK.blocked_user_id , I've tried this, but result is empty: 我想在BLOCK.blocked_user_id选择帖子的评论和COMMENT.comment_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()

As alternative solution, I have to use two query steps, first step to select all blocked_users, second step to select post's comments filter by 作为替代解决方案,我必须使用两个查询步骤,第一步选择所有blocked_users,第二步选择发布者的评论过滤条件

COMMENT.comment_user_id.notin_(blocked_users)

assuming you can use session for sqlalchemy below query will return you the correct result as you taking left join on comment and block table 假设您可以在下面的查询中将会话用于sqlalchemy,则在对注释和块表进行左连接时将返回正确的结果

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

so your original query will get something like below 这样您的原始查询将得到如下所示的内容

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

Note : above query only filter all comments with userid which is not blocked table you can add your more filter conditions as per your requirement for other columns 注意:上面的查询仅过滤具有userid的所有注释(未阻止表),您可以根据对其他列的要求添加更多过滤条件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM