我有三个桌子。 用户: 包含user_id,用户名,profileimg
帖子: 包含user_id(发帖人),posted_at (日期),postimg,id
朋友: 包含user_a_id和user_b_id
我很努力地撤出所有用户朋友和用户本人发布的帖子。 因此,查询中唯一的输入是用户的ID。
我尝试使用联接,但在理解联接及其语法时遇到麻烦。
我也尝试使用其他人的查询,只是试图使它们适应我的情况,如果我失败了哈哈
答案 0 :(得分:0)
您需要编写嵌套查询
select * from Posts where user_id in (select user_b_id from Friends where user_a_id = 'MY_USER_ID') OR Posts.user_id = 'MY_USER_ID'
答案 1 :(得分:0)
因为帖子只有一个user_id
,所以效果最好的方法可能是使用union all
:
select p.*
from posts p
where p.user_id = :user_id
union all
select p.*
from posts p
where exists (select 1
from friends f
where f.user_a_id = :user_id and f.user_b_id = p.user_id
);
这假设您“用户的朋友”的意思是“ user_b_id
,当您知道user_a_id
时”。也就是说,如果A和B是朋友,则friends
表中同时有A / B和B / A。
尤其是,此查询可以利用posts(user_id)
和friends(user_a_id, user_b_id)
上的索引。
答案 2 :(得分:0)
将表posts
结合到一个查询中,该查询返回用户和朋友的ID:
select distinct p.*
from posts p inner join (
select * from friends
where ? in (user_a_id, user_b_id)
) f on p.user_id in (f.user_a_id, f.user_b_id)
或:
select distinct p.*
from posts p inner join friends f
on p.user_id in (f.user_a_id, f.user_b_id)
and ? in (f.user_a_id, f.user_b_id)
将?
替换为搜索用户的ID。