2016-12-19 32 views
1

我在我的mysql数据库(用户,关注者,发布)上有3个表,我写了一个sql,获取用户所关注人员的所有帖子。从两个以上的表中选择使用连接选择重复项

SQL

SELECT post.* FROM post JOIN 
     follower ON post.owner_user_id = follower.user_id AND 
     follower.follower_id = "3" 

结果

id | owner_user_id | content 
2 | 1    | why are all my senior developers jerks? 
3 | 1    | PHP7 in your face node.js 

用户表

id | username | password 
1 | user1 | 12345678 
2 | user2 | 12345678 
3 | user3 | 12345678 

FOL下表

user_id | follower_id 
3  | 1 
3  | 2 
1  | 3 

交表

id | owner_user_id | content 
1 | 2    | reading a 1k+ page on mysql, do i need to? 
2 | 1    | why are all my senior developers jerks? 
3 | 1    | PHP7!, in your face node.js 
3 | 3    | I posted 

所以现在我想选择的人的用户在下面的帖子和用户的

我想这SQL的帖子

sql

SELECT post.* FROM post JOIN 
     follower ON post.owner_user_id = follower.user_id AND 
     follower.follower_id = "3" JOIN 
     user ON post.owner_user_id = user.id= "3" 

结果

null 

请就是想实现与SQL可能, 如果(可能){ “what_am_i_doing_wrong”}();

编辑

user_id 3 has a post, still running the above sql returns null, was hoping if the user had no post, only post of the people the user is following is returned 
+0

你为什么不使用'WHERE'条件? – Option

+0

你没有得到任何东西,因为没有价值3的owner_user_id –

+0

@shanu k k但我不是想要得到用户的追随者后? –

回答

2
select post.* from 
(select user_id from follower where follower_id = 3 union select 3) blah 
join post on blah.user_id = post.owner_user_id; 
+0

哇,这项工作就像魔术字面上的魔法一样,我的桌子上没有“嗒嗒”声,怎么这样做不会返回错误,我在mysql中学到了很多东西。 OOh,谢谢! –

+0

这是一个别名。您可以将其更改为更有意义的标识符。 – siloko

+0

我可以在twitter上关注你吗?或你的网站。 –

1

试试这个:

SELECT Distinct post.* FROM post JOIN 
    follower ON post.owner_user_id = follower.user_id JOIN 
    user ON follower.user_id = user.id WHERE user.id = 3 

您shuldn​​'t使用条件JOIN语句,使用WHERE代替。

+0

我试过这个,但它返回了用户3的帖子的2个重复。没有什么更多 –

+0

你想回报什么?回答更新,检查它 –

+0

现在它只是返回单个用户3的帖子,但我试图返回用户3的帖子和用户3的帖子后面。 siloko的答案就是这样做的,谢谢你的回答,尽管我很欣赏。 –