SQL Database for related family members

耗尽温柔 提交于 2019-12-08 08:57:40

问题


I am curious what you think is the best way to get this MySQL database to work.

i had this table:

family.id
family.name
family.related

And thought it wouldnt be a problem to connect related family members together in 1 query like this:

id        | name        | related
1         | Name1       | 
2         | Name2       | 3,5
3         | Name3       | 
4         | Name4       | 
5         | Name5       | 4,1
6         | Name6       | 
7         | Name7       | 
8         | Name8       | 6
9         | Name9       | 7

So Name2 is related to Name3 and Name5, where Name5 have other related id's, so i should make a query to get the following id's:

Selecting id 2, outputs related id's: 3,5,4,1

Selecting id 6, outputs related id's: 8

Selecting id 9, outputs related id's: 7

But i cant find a query to get all the related id's in one column.

Is it even possible?


回答1:


For a many-to-many relationship, you'll generally need to use a linking table:

family_id
related_to

Where, when you would have several comma-delimited items in your family table, you would instead have one entry in the linking table for each item that would be in the comma-delimited list:

family_id | related_to
2           3
2           5
5           4
5           1
...

And so on.



来源:https://stackoverflow.com/questions/15910905/sql-database-for-related-family-members

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!