2017-02-11 75 views
0

我有3個表大致如下圖所示:SQL得到的所有條目由IDS

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用戶的​​得到的所有帖子,可以是多個用戶。我可以在SQL中完成嗎?

回答

0

如果您知道關注者的ID,以下語句將進行連接並獲取關注者的關注者的帖子。您可以用任何用戶ID替換數字3。

SELECT * FROM user_following AS a 
    JOIN post AS b ON a.followee = b.author 
    WHERE a.follower=3; 
0

像這樣的東西?

select p.* 
from post p 
join user_following uf on p.author = uf.followee 
where uf.follower = 123; 
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