[英]SQL - Joining 3 table query
Good day everyone, 今天是个好日子,
This is my first post on stackoverflow. 这是我关于stackoverflow的第一篇文章。 Honestly, the community is great and full of knowledge.
老实说,社区很棒,知识渊博。 I usually get on it but never made any posts until today I decided to register an account.
我通常会上它,但是直到今天我决定注册一个帐户之前,我从未发表过任何帖子。 I need the knowledge of this amazing community for a small quick join query.
我需要这个惊人社区的知识,可以进行小型快速加入查询。
For some odd reason I am not able to get it to work. 由于某些奇怪的原因,我无法使其正常工作。
Here is the relationship table: 这是关系表:
What I am trying to output (In this example I will use userID 10): 我要输出的内容(在此示例中,我将使用用户ID 10):
Display tweet from the Tweet table of all the user the userID 10 follows (including the userID 10 itself) 显示用户ID 10遵循的所有用户的推文表中的推文(包括用户ID 10本身)
In other words: Assume userID 10 is called Bob and Bob follows Bell and Rogers. 换句话说:假设用户ID 10被称为Bob,而Bob紧随Bell和Rogers。
So I'd like to output the tweet of Bob, and everyone Bob follows: Bell and Rogers 所以我想输出Bob的推文,每个Bob都会关注:Bell和Rogers
Thank you in advance for your help and time :) 预先感谢您的帮助和时间:)
EDIT: 编辑:
My apologies! 我很抱歉! Here is the sample data:
这是示例数据:
Sample Data 样本数据
Thank you once again :) 再一次感谢你 :)
Without sample data it's hard to be certain but this query should work. 没有示例数据,很难确定,但是此查询应该可以工作。 It selects all tweets from the table which match a userID (1) or anyone who that user is following:
它从表中选择与userID(1)或该用户关注的任何人匹配的所有推文:
SELECT DISTINCT t.*
FROM User u
JOIN Follow f ON f.follower = u.userID
LEFT JOIN Tweet t ON t.userID = u.userID OR t.userID = f.following
WHERE u.userID = 1
Output (for your sample data) 输出(用于样本数据)
tweetID userID tweet
1 1 Hello
2 4 Hey
3 1 Hi Folks!
6 4 Something
7 3 Heya!
This will select tweet text of the user 10 and anyone he follows. 这将选择用户10和他关注的任何人的推文。 Note that you need to put ID on 2 places.
请注意,您需要在2个地方放置ID。
SELECT t.userID, t.tweet FROM Tweet t
INNER JOIN
(SELECT following FROM Follow WHERE follower=10) uf
ON t.userID=uf.following
UNION
SELECT ut.userID, ut.tweet FROM Tweet ut
WHERE ut.userID=10
output (userID, tweet): 输出(用户ID,tweet):
3 tweet2
2 tweet3
1 tweet1
This should work: 这应该工作:
select t.tweet
from tweet t inner join
(select b.userid,a.following
from follow a inner join users b
on a.follower = b.userid) u
on t.userid = u.following
where u.userid = 1 or t.userid = 1
order by t.date,tweet
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.