Search code examples
mysqlsqlinner-joinrelationshipjoin

SQL - Joining 3 table query


Good day everyone,

This is my first post on 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:

Click here to view the relationship between tables

What I am trying to output (In this example I will use userID 10):

Display tweet from the Tweet table of all the user the userID 10 follows (including the userID 10 itself)

In other words: Assume userID 10 is called Bob and Bob follows Bell and Rogers.

So I'd like to output the tweet of Bob, and everyone Bob follows: Bell and Rogers

Thank you in advance for your help and time :)

EDIT:

My apologies! Here is the sample data:

Sample Data

enter image description here

Thank you once again :)


Solution

  • 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:

    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!
    

    Demo on dbfiddle