One approach might be that you create a second table that stores the person and friend identifiers. In this case, consider the following tables.
CREATE TABLE User ( id int auto_increment primary key, name varchar(20) ); CREATE TABLE Friend ( user_id int , friend_id int ); INSERT INTO User (name) VALUES ('Julie'), ('Adam'), ('David'), ('John'), ('Sam'); Insert INTO Friend (user_id, friend_id) values(1, 5), (3, 1);
The Friend table will now store user_id and his / her friend_id. To get a friend list for a specific user, you can search for matching identifiers in either of these two columns. The following are sample queries.
-- Get Friends of Julie select 1 AS user_id, IF(user_id = 1, friend_id, user_id) AS friend_id FROM Friend WHERE user_id=1 OR friend_id=1; -- Get Friends of David select 3 AS user_id, IF(user_id = 3, friend_id, user_id) AS friend_id FROM Friend WHERE user_id=3 OR friend_id=3
I hope you get an idea about this and can play.
Riz
source share