简体   繁体   English

SQL-检索朋友的用户数据

[英]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. 如果用户有例如2个朋友,则查询将响应2行,但同时显示当前登录用户的用户数据。 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: 我认为您希望join friend列而不是userId列:

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";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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