Mysql join from multiple tables

后端 未结 4 1974
半阙折子戏
半阙折子戏 2021-01-16 16:43

I have 3 tables

friends
posts
members

friends
========
id, to, from (user_id\'s), status

there are 3 status\'s -1 = denied, 0 = no response/new, 1 = accept         


        
相关标签:
4条回答
  • 2021-01-16 17:03

    I added a subquery to get all your friends since I assumed that if you have these records

    Friends
    ==================================
    ID      TO       FROM     STATUS
    ==================================
    1       1        2         1
    2       3        1         1
    

    and your member_id = 1, your friends are 2, 3. right?

    SELECT  b.f_name,
            b.L_name,
            c.`text`
    FROM
        (
            SELECT `to` friendID
            FROM    friends
            WHERE   `status` = 1 AND
                    `from` = ?             -- change this to your ID
            UNION
            SELECT `from` friendID
            FROM    friends
            WHERE   `status` = 1 AND
                    `to` = ?               -- change this to your ID
        ) a  INNER JOIN members b
                ON a.friendID = b.member_ID
            LEFT JOIN   posts c
                ON a.friendID = c.user_id
    
    0 讨论(0)
  • 2021-01-16 17:06

    As I understand it, you want to find the name and posts of all your friends, not any friend that's in the friend table at all...?

    Your own user id being in $myId, this should do it (newest posts first);

    EDIT: Added status check for friends

    SELECT m.f_name, m.l_name, p.`text`
    FROM members m
    JOIN posts p 
      ON m.member_id = p.user_id
    JOIN friends f 
      ON f.`to` = m.member_id OR f.`from` = m.member_id
    WHERE (f.`from` = $myId OR f.`to`= $myId)
      AND f.`status` = 1 AND m.member_id <> $myId
    ORDER BY p.p_id DESC
    
    0 讨论(0)
  • 2021-01-16 17:06

    Try this :

        SELECT p.text,m.f_name,m.l_name FROM posts p 
        LEFT OUTER JOIN members m ON p.user_id=m.member_id
        where p.user_id in(select id from friends);
    
    OR
    
       SELECT p.text,m.f_name,m.l_name FROM posts p 
       LEFT OUTER JOIN members m ON p.user_id=m.member_id
       INNER JOIN friends f on p.user_id=f.id
    
    0 讨论(0)
  • 2021-01-16 17:09

    If I understand correctly, you have a user_id and you want all the posts authored by "friends" of that user. This query starts at posts, joins that to friends (where the author is the "destination" of the friendship) (at which point the WHERE clause will filter out any non-friend posts), and then joins in members to fill out the author's name info.

    SELECT 
      posts.p_id
      posts.text,
      CONCAT(members.f_name, " ", members.l_name)
    FROM 
      posts
      JOIN friends ON posts.user_id = friends.to
      JOIN members ON posts.user_id = members.member_id
    WHERE
      friends.from = ?
    GROUP BY posts.p_id
    
    0 讨论(0)
提交回复
热议问题