I have a question about MySQL. I have this table structure:
ID Name
------ ------------
1 Peter
2 John
3 Carl
4 William
I need to link the record.
I.e.
– Peter is related to Carl and William
– Carl is related to John
Should I make a new table like this:
ID1 ID2
------ ------------
1 3
1 4
3 2
Or should I extend the first table like this:
ID Name Links
------ ------------ ----------
1 Peter 3,4
2 John
3 Carl 2
4 William
In both cases, how do I make a query that returns:
Name LinkedName
------------ --------------
Peter Carl
Peter William
I have considered to use JOIN, UNION and sub-queries, but I can not really get it to work.
I really hope that somebody can help me here.
Thanks.
As it is an n:m relationship (“Peter is related to Carl and William”), your first idea is the right one: an additional table with two IDs. You could add further information about the relationship there. Also add foreign keys and a primary key to prevent duplicate entries.
Query like this: