简体   繁体   中英

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

SQLAlchemy for MySQL without foreign key, I've created these tables:

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:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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