0

I searched several examples on the web and still need some help after researching. I have 2 tables: users and friends.

the users table has columns:

  • id bigint(20)UNSIGNED AUTO_INCREMENT
  • username varchar(50)
  • profile_picture varchar(200)
  • status varchar(20)
  • status_message varchar(200)

the friends table has columns:

  • id bigint(20) UNSIGNED AUTO_INCREMENT
  • initiator_user_id bigint(20)
  • friend_user_id bigint(20)

I want to be able to get the username, profile_picture, status, status_message from all users who are friends (friend_user_id) of a specified user (initiator_user_id). After researching I believed this is done with a union.

I have tried the query below but it doesn't work:

SELECT friend_user_id 
FROM friends
WHERE initiator_user_id = 1001 //gets all the id's of the friends of user 1001
UNION All
SELECT profile_picture, status, status_message, username from users
WHERE friend_user_id = id //gets all the profile data of user's profiles that are friends of user 1001

What I need is for the friends data to be displayed for all friends:

  • id bigint(20)UNSIGNED AUTO_INCREMENT
  • username varchar(50)
  • profile_picture varchar(200)
  • status varchar(20)
  • status_message varchar(200)

My questions:

  • Does anything need to be changed regarding the tables (any foreign key constraints...etc.)?
  • What do I need to change to make this example work?
1
  • No, it's not done using a UNION. It's done using a JOIN.
    – Barmar
    May 1, 2014 at 2:37

1 Answer 1

0

Use a simple INNER JOIN:

SELECT u.*
FROM users AS u
INNER JOIN friends AS f ON f.friend_user_id = u.id
WHERE f.initiator_user_id = 1001
2
  • Thanks a lot this worked perfectly. Now the only thing I don't understand is why developers add foreign key constraints and things of that matter. Is there an advantage to adding constraints of that type? May 1, 2014 at 2:53
  • It allows the database to ensure that the data is correct. If there's a bug in the code that tries to create a friend pointing to a nonexistent user, the database will report an error. This is called referential integrity.
    – Barmar
    May 1, 2014 at 2:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.