Mysql 父表和子表
如果这个话题已经被提出,我很抱歉 要求是:我正在创建一个家谱系统,我需要为其他人保留一个人的详细信息,可以是父母和/或孩子。例如,personA是personB的父级,personB是personC的父级(personA->personB->personC)。我对上述要求的mysql版本是 人Mysql 父表和子表,mysql,Mysql,如果这个话题已经被提出,我很抱歉 要求是:我正在创建一个家谱系统,我需要为其他人保留一个人的详细信息,可以是父母和/或孩子。例如,personA是personB的父级,personB是personC的父级(personA->personB->personC)。我对上述要求的mysql版本是 人 |id |person_name| 1 | personA 2 | personB 3 | personC 我的父母 |id | person_id | parent| 1 | 3 | 2
|id |person_name|
1 | personA
2 | personB
3 | personC
我的父母
|id | person_id | parent|
1 | 3 | 2
2 | 2 | 1
但我觉得这不对。任何mysql专家都可以给我一些更好的建议,并提供一个sql语句来迭代检索person层次结构。谢谢您实际上不需要两张桌子。相反,它通常是通过一个表来完成的,该表的父表列引用了同一个表中的另一个
person\u id
:
表人员
要查询它,请对其自身使用JOIN:
SELECT
child.person_name AS childname,
child.person_id,
parent.person_name AS parentname
FROM
/* First use of the table for the child */
people AS child
/* JOIN against the same table to get the parent's name */
/* LEFT JOIN is used in case the parent_id is NULL and the parent is unknown */
LEFT JOIN people AS parent ON child.parent_id = parent.person_id
产生:
childname | id | parentname
-----------|----|-------------
JSmith Jr | 1 | JSmith Sr
JSmith Sr | 2 | Grandpa
Grandpa | 3 | NULL
更新以允许多个父级,请使用2个表:
表人员
:
person_id | person_name
1 | JSmith Jr
2 | JSmith Sr
3 | Grandpa
4 | Grandma
5 | MomSmith
表关系
:
person_id | parent_id | relationship
1 | 2 | father
1 | 5 | mother
2 | 3 | father
2 | 4 | mother
要查询母亲和父亲,请执行以下操作:
SELECT
child.person_id,
child.person_name AS childname,
mother.person_name AS mothername,
father.person_name AS fathername
FROM
people AS child
JOIN relationships AS rc ON child.person_id = rc.person_id
LEFT JOIN people AS mother ON rc.parent_id = mother.person_id AND relationship = 'mother'
LEFT JOIN people AS father ON rc.parent_id = father.person_id AND relationship = 'father'
未经测试,但应产生:
person_id | childname | mothername | fathername
1 | JSmith Jr | MomSmith | JSmith Sr
2 | JSmith Sr | Grandma | Grandpa
3 | Grandpa | NULL | NULL
4 | Grandma | NULL | NULL
5 | MomSmith | NULL | NULL
最好使用关系表,因为一个人可以有多个父母。@xdazz Yes在本例中可能是这样。我在要求中遗漏了复数形式的“其他人的孩子”。@Michael谢谢你的快速依赖,我不知道桌子可以连接到自己,我今天学习了新东西。@xdazz你能给我举个例子说明你会怎么做吗,thanks@user1152967请参阅上面的添加-我添加了一个从两个表查询多个父表的方法。
person_id | childname | mothername | fathername
1 | JSmith Jr | MomSmith | JSmith Sr
2 | JSmith Sr | Grandma | Grandpa
3 | Grandpa | NULL | NULL
4 | Grandma | NULL | NULL
5 | MomSmith | NULL | NULL