简体   繁体   English

使用联接从两个以上的表中进行选择会选择重复项

[英]Selecting from more than two tables using join selects duplicates

I have 3 table on my mysql db (user, follower, post), I wrote an sql, that get all posts from the people a user followed. 我在mysql db(用户,关注者,发布)上有3个表,我写了一个sql,该列表从用户关注的人那里获取所有发布。

sql sql

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

result 结果

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

user table 用户表

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

follower table 追随者表

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

post table 发布表

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

so now am trying to select post of people the user is following and the posts of the user 所以现在尝试选择用户关注的人的帖子以及用户的帖子

I tried this sql 我试过这个SQL

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"

result 结果

null

Please is what am trying to achieve with the sql possible, if(possible) {"what_am_i_doing_wrong"}(); if(可能){“ what_am_i_doing_wrong”}();

edits 编辑

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
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;

Try this: 尝试这个:

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

You shuldn't use conditions in JOIN statement, use WHERE instead. 您不应在JOIN语句中使用条件,而应使用WHERE。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM