简体   繁体   中英

SQL - Retrieve user data of friends

I want to display the user's list of friends with username, gender etc. After a user registers he get´s stored in this table:

USER |id |username |age |gender

If he adds a friend a friendship is inserted to my database like so:

FRIENDS
friendShipId
userId (the id from the user who is logged in and want to show his friends)
friend (the id of the user who the currently loggedInUser is friends with)

Now I need to get a list of friends of the logged in user:

SELECT users.username, users.age, users.gender, friends.friendshipId, friends.friend 
FROM friends INNER JOIN users 
ON friends.userId = users.id 
WHERE friends.userId = $id"

If the user got eg 2 friends, the query responds 2 rows but both with the userdata of the current loggedIn user. Not with the data of his friends. Could you help me?

I think you want the join on the friend column, not the userId column:

SELECT u.username, u.age, u.gender, f.friendshipId, f.friend 
FROM friends f INNER JOIN
     users u       
     ON f.friend = u.id 
WHERE f.userId = $id";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM