简体   繁体   中英

Querying friends for a user based on self-referencing table

I have a user table and a self-referencing table so users can be assigned as friends to each other. The table looks like this:

数据库模型-Image.frl-免费图像托管
(source: image.frl )

I want to query the table and get back all the friends for a particular user (for example by user id). I'm not sure how to query it in a way that it knows that it should look for all the friend id's for the user id and lookup all the users that are associated with those friend id's in the user table.

Can anyone shed a light on how this can be done? I'm using MySQL.

The simple answer to your question (a look up by user_id) is this

SELECT friends.*
FROM user AS friends
JOIN user_has_friends ON friends.id = user_has_friends.friend_id
WHERE user_has_friends.user_id = *ID HERE*

You'd have to add another join to the users table if you wanted to look up by first_name or any other column.

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