我有3张大致如下表:
create table user(
id integer primary key
)
create table post(
id integer primary key,
author integer,
foreign key (author) references user(id)
)
create table user_following(
id integer primary key,
follower integer,
followee integer,
foreign key (follower) references user(id),
foreign key (followee) references user(id)
)
这些表是由ORM框架创建的,我想使用原始SQL来获取用户followee
的所有帖子,这些用户可以是多个用户。我可以在SQL中执行吗?
答案 0 :(得分:0)
这样的东西?
select p.*
from post p
join user_following uf on p.author = uf.followee
where uf.follower = 123;
答案 1 :(得分:0)
如果您知道关注者的ID,则以下声明将进行加入,并获得关注者的跟随者'帖子。您可以使用任何用户ID替换数字3。
SELECT * FROM user_following AS a
JOIN post AS b ON a.followee = b.author
WHERE a.follower=3;
答案 2 :(得分:0)
select posts.*
from post posts
inner join [user] u_followee on u_followee.id = posts.author
inner join user_following ufo on ufo.followee = u_followee.id
inner join [user] u_follower on ufo.follower = u_follower.id
where u_follower.id = @USER_ID_WHOSE_FOLLOWEE_POSTS_REQUIRED