我有 3 个表格 - 帖子、友谊和喜欢 - 下面描述的重要字段。
帖子:id, user_id, title
友谊:requester_id, accepter_id, is_confirmed
喜欢:post_id, user_id
我有一个名为 get_relevant_posts() 的方法,它应该返回我写的、我确认的朋友写的或者我确认的朋友喜欢的帖子。我已经在 SQLAlchemy 中实现了这个,但是我的查询中有一个错误,因为它只有在友谊表不为空时才有效(不管里面有什么,只是不能为空)。如果它为空,则不会返回任何内容(不正确的连接?)。
这不是一个大问题,因为友谊表中 99.99% 的时间都会有一些东西。但我仍然想退后一步,用普通的 SQL 来写这个——我似乎无法理解它。
SQLALCHEMY 代码
Friendship1 = aliased(Friendship)
Friendship2 = aliased(Friendship)
Friendship3 = aliased(Friendship)
Friendship4 = aliased(Friendship)
return (DBSession.query(Post)
.outerjoin(Friendship1, Post.user_id==Friendship1.accepter_id)
.outerjoin(Friendship2, Post.user_id==Friendship2.requester_id)
.outerjoin(Like, Post.id==Like.post_id)
.filter(or_(
# My post
self.id==Post.user_id,
# My friends post, where I'm the requester of the friendship
and_(self.id==Friendship1.requester_id,
Friendship1.is_confirmed==True),
# My friends post, where I'm the accepter of the friendship
and_(self.id==Friendship2.accepter_id,
Friendship2.is_confirmed==True),
# Somebodies post, which my friends found interesting
and_(self.id==Friendship3.requester_id,
Friendship3.is_confirmed==True,
Like.user_id==Friendship3.accepter_id),
and_(self.id==Friendship4.accepter_id,
Friendship4.is_confirmed==True,
Like.user_id==Friendship4.requester_id)))
.order_by(Post.created_at.desc())
.limit(limit)
.offset(offset)
.all())
产生这个
SELECT posts.title AS posts_title
FROM friendships AS friendships_1, friendships AS friendships_2, posts LEFT OUTER JOIN friendships AS friendships_3 ON posts.user_id = friendships_3.accepter_id LEFT OUTER JOIN friendships AS friendships_4 ON posts.user_id = friendships_4.requester_id LEFT OUTER JOIN likes ON posts.id = likes.post_id LEFT OUTER JOIN users AS users_1 ON users_1.id = posts.user_id
WHERE (posts.user_id = %s OR friendships_3.requester_id = %s AND friendships_3.is_confirmed = %s OR friendships_4.accepter_id = %s AND friendships_4.is_confirmed = %s OR friendships_1.requester_id = %s AND friendships_1.is_confirmed = %s AND likes.user_id = friendships_1.accepter_id OR friendships_2.accepter_id = %s AND friendships_2.is_confirmed = %s AND likes.user_id = friendships_2.requester_id) ORDER BY posts.created_at DESC
LIMIT %s