SQL join help for friend list

后端 未结 4 1205
猫巷女王i
猫巷女王i 2021-01-18 18:41

I have three database tables: users, user_profiles and friends:

users

  • id
  • username
相关标签:
4条回答
  • 2021-01-18 19:00

    Falling back on bad habits (not using JOIN notation in the FROM clause):

    SELECT a.id, a.username, a.full_name,
           b.id, b.username, b.full_name
      FROM friends AS f, users AS ua, users AS ub,
           user_profiles AS a, user_profiles AS b
     WHERE f.usera_id = ua.id
       AND f.userb_id = ub.id
       AND a.user_id  = ua.id
       AND b.user_id  = ub.id
    

    The key point is using table aliases (all those 'AS' clauses) and referencing the same table more than once when necessary.

    Someone could write this with JOIN instead.

    0 讨论(0)
  • 2021-01-18 19:10

    Some modification to eugene y's answer, will this work?

    SELECT * FROM users u
    JOIN friends f ON (f.userb_id = u.id OR f.usera_id = u.id)
    JOIN user_profiles p ON u.id = p.user_id
    WHERE u.id = ?
    
    0 讨论(0)
  • 2021-01-18 19:13

    This may not be the best way to do it, but this felt like the logical way:

    select a.id , a.friend_id ,
    Users.username
    from
     ( SELECT id , IF(usera_id = 1, userb_id , usera_id) friend_id
     FROM friends
     where usera_id = 1 OR userb_id = 1 ) a
    left join Users on a.friend_id = Users.id
    

    this uses a mySQL function so probably wont work in Oracle/MSSQL

    0 讨论(0)
  • 2021-01-18 19:19

    Use:

    SELECT f.username,
           up.*
      FROM USERS f
      JOIN USER_PROFILES up ON up.user_id = f.id
      JOIN FRIENDS fr ON fr.userb_id = f.id
      JOIN USERS u ON u.id = fr.usera_id
     WHERE u.username = ?
    

    ...assuming userb_id is the friend id.

    0 讨论(0)
提交回复
热议问题