简体   繁体   中英

Linking two rows from same table MYSQL

As an example, let's say I want users to be friends on the website.

Say, user_id 1 and user_id 2 become friend, I add a row to my table friends: table friends (user_id1 INT, user_id2 INT), the problem with this table is that I have to query each column to get my results.

Rows may be:

  user_id1    user_id2
  1           2
  2           3

So to get friends of user with id 2, I need to query both columns (which make some not so practical queries), is there a better way to do this?

 ie:
  $u_id = 2;
  SELECT * FROM friends WHERE (user_id1 = $u_id OR user_id2 = $u_id)

You could try a different approach, storing all friends of a person inside a field friends in the table and storing everything as a json object.

This way you'd have all one person's friends in a single query and you could get tehir profile with a simple foreach query.

I've been using this for several many-to-many logics and it works flawlessly without the aid of a link table.

I think I'd prefer a UNION , something like:

SELECT user, friend FROM ( SELECT user_id1 AS user, user_id2 AS friend FROM friends UNION SELECT user_id2 as user, user_id1 AS friend FROM friends ) u WHERE u.user = $u_id

(with appropriate caveats about using prepared statements instead of bare variables of course)

I would go for the less space efficient method of adding two rows one linking person A to person B and the second linking person B to person A. Then a single query on a single column will retrieve all friends.

This set up can also be used where "friends" have different privileges or levels of friendship. So person A can give B more access to their stuff than B gives to A.

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