Struggling with getting data from 3 tables

Discussion in 'MySQL' started by homemadejam, May 18, 2012.

  1. #1
    Hey,
    I haven't done any sort of SQL in a very long time, so I am struggling to remember everything.
    I have been stuck on this problem for hours and hours now. If anyone could help me out, or point me in the right direction, I would be very grateful.

    I have the following 3 tables:

    users(user_id, username)
    gossip(user_id, content)
    friendships(friendship_id, user_id, friend_id)


    And what I'm wanting is for all the gossip to be shown for both yourself, and the people you are friends with.
    The sort of effect I am going for is like your twitter time line. Not only can you see your tweets, but also your followers tweets.

    The only information I want to be displayed is the gossip content, and the username of who posted it.

    Now I really have no idea how to achieve this.
    I think I have posted everything that will be relevant.

    Thanks in advance,
     
    Solved! View solution.
    Last edited: May 18, 2012
    homemadejam, May 18, 2012 IP
  2. #2
    I didn't actually build the tables to test this, but I believe it will give you what you are wanting based on the table definitions you provided: (of course, replace "<your user id>" with the actual id value)

    
    SELECT u.username
          ,g.content
      FROM users u
          ,gossip g
     WHERE g.user_id = u.user_id 
       AND(
           u.user_id = <your user id>
        OR u.user_id = (SELECT f.friend_id
                          FROM friendships f
                         WHERE f.user_id = <your user id>)
          )
    
    Code (markup):
    This should retrieve all the "gossip" entries associated with your user id, or with the friend ids that you are friends with.
     
    DaySeven, May 22, 2012 IP