¿Cuál sería el mejor algoritmo para obtener la información usando PHP y MySQL?

I am trying to find a better algorithm here. In my problem, a user has 200 friends in his list. My database looks like this:

    username          friends
     someid           2,3,4,6,7

What I did is when a new friend is added. The persons unique id is added to his list so here 2,3,4,6,7 are the ids of the users friends.

And the normal users info database looks like this

   friends info 
    id     profile image    name               info
    2         his image    his name       presently

My algorithm is get the id 2 and fetch all the data from the table putting id = 2 then similarly 3,4,6 and more but if user has 200 friends, I was thinking it may cause a serious issue on server it keeps server busy because it should fetch data for 2 and again for 3.

So I was thinking for a better algorithm because if user has more friends the server have to perform MySQL (select * ) statement for 200 times if they are 200 friends this may cause a serious server issue.

I want to know if there is a simple algorithm to do or may be should I change the way how data is saved on database?

Sometimes I think to fetch and store all the data in a php variable and then save it to JavaScript variable and then using JavaScript perform the operations, because JavaScript is client side and removes server issue.


Is the size of table is limited? I mean can a table consist of infinite rows?

  user id       friend id
    2                3
    2                4
users_info table
  user id           image           small info
     3            some image             // 
     4              //                   //
     2                 //                //

As people suggested I would change the structure but how do I link friends_tabe to users info table?

   $result = mysql(select * from friends_table where id = userdid);
   $row = mysql_fetch_array($result);

above query gets all the ids of friends

Now I have to get the friends info using their id so I have to perform this statement

   for($i=0 ;$i<count($row);$i++)
   mysql(select * from users_info where id=$row[$i])

I think I should perform this statement so many times. In other words, do I have to loop this statement?

preguntado el 02 de febrero de 12 a las 11:02

Best algorithm is to change your database structure, and use one row for cada user/friendid rather than that comma separated list - what you've done Siempre hay leads to problems -

@MarkBaker i appreciate your help but could you help me out with a solution explaing the strcture of database? -

5 Respuestas

Instead of storing ids of all friends in one column create a muchos a muchos relationship with table that maps users to their friends.

user_friends table:

| user_id  | friend_id |
|  someid  |     2     |
|  someid  |     3     |
|  someid  |     4     |
|  someid  |     6     |
|  someid  |     7     |

Then you can select all friends info in one query

SELECT `friends_info` * from `friends_info` 
LEFT JOIN user_friends ON user_friends.friend_id = friends_info.id
WHERE user_friends.user_id = someid

You can use the query like that:

$result = mysql_query("<the query goes here>"); // Execute the query

while ($row = mysql_fetch_array($result, MYSQL_NUM)) { // For each row..
   (...)    // ...do sth with the data


Respondido 02 Feb 12, 15:02

Use the query from my answer to avoid looping. It fetches all related rows at once for given user_id. I've added PHP code to handle it. - Mariusz Jamro


username    friends 
someid      2,3,4,6,7


username    friendid
someid      2
someid      3
someid      4
someid      6
someid      7

select users.*
  from users,
 where users.id = friends.friendid
   and friends.username = someid

gets all the friend details in a single SQL query

Respondido 02 Feb 12, 15:02

Usage of JOINs have better performance that SELECTing from two tables, especially when the tables are large. - Mariusz Jamro

Perhaps, though I am using a simple inner join. Performance would have to be tested... but I was more concerned with demonstrating that a normalised table was better than a comma-separated list of friends - Mark Baker

I wouldn't recommend sending all information to the client for it to figure it out itself, because the visitors would be able to see all data - it's not very secure. In this case, they could see everybody's friends.

Instead of saving all friends' ID's in a varchar (which I think you're doing now?) you should create a new 'Friends' table with two columns: the ID of the user, and the ID of their friend. This would mean that per relationship, there would be a new record in that table. This would be, despite the additional number of records and even a table, a faster way of storing this - and a much neater way (read http://en.wikipedia.org/wiki/Database_normalization).

User ID | Friend ID
 1      |  2
 1      |  3
 2      |  3
 3      |  2

Searching these tables wouldn't take a long time. Especially with just 200 users, this won't be an issue at all (I doubt it would be with your current set up, too).

Respondido 02 Feb 12, 15:02

Don't use a comma separated list of friends: add a table FRIENDS as

    id        friend_id
    9          2
    9          4
    9          7
    9          5
    2          3
    2          7

and so on. Let the database do the works for you.

Respondido 02 Feb 12, 15:02

You can use "in" base condition in fething Select * from user where userid in[2,4,5,8];

Respondido el 07 de diciembre de 15 a las 12:12

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.