Diseño de tabla mysql con múltiples valores para la misma columna

I am integrating a friends system for my website...

One question I have about the mysql table is how it is to be set up.

Will I have many columns for each friend they add, such as freind 1, 2, 3, 4, 5 and so on and the row will be the user who has added them.

Is there a better way to do this?? With my first thought doing it that way would mean a cap on the amount of friends someone can have...

preguntado el 27 de agosto de 11 a las 15:08

Doing that you would have a 1-row table wouldn't you ? That is not really clever DB design. I'm thinking about something like 1 table (id, friend.id, friend_id_who_added) and other table friend (id, name) -

2 Respuestas

Your suggestion of multiple columns would violate primera forma normal. As well as artificially restricting the number of friends such structures are tedious to work with and inefficient.

You need a junction table for friends with 2 columns (userid1,userid2) that form a composite primary key. Both columns would have a FK relationship with the user mesa.

In many RDBMSs you would also have a check constraint userid1 > userid2 so a relationship can only be stored in one form but I believe check constraints are somewhat broken in MySQL.

contestado el 23 de mayo de 17 a las 14:05

+1: Only caveat is the composite primary key won't stop reverse duplicates. IE: 1,2 and 2,1 are considered valid composite PK values - Ponis dios mio

Ok do you have any links to where I could learn this technique, thanks - carlgcoder

@carlgoder - The gist of my answer is really about normalisation. Worth reading the wiki articles on primeras, segunda y tercera normal forms. - Martin Smith

You will need an additional table with records for each friend a member has. For example:

members (id, name)
friends (member1, member2)

Respondido 27 ago 11, 19:08

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