![](/img/trans.png)
[英]Selecting and displaying date from two tables using JOIN and an associative ID
[英]Selecting from more than two tables using join selects duplicates
我在mysql db(用戶,關注者,發布)上有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
追隨者表
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
if(可能){“ 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
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;
嘗試這個:
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
您不應在JOIN語句中使用條件,而應使用WHERE。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.