父母和子女表

时间:2012-01-17 02:04:23

标签: mysql

如果已经提出这个话题,我很抱歉。

要求是这样的:我正在创建一个家谱系统,我需要将一个人的详细信息保存给其他人,这可以是父母和/或孩子。例如,personA是personB的父亲,personB是personC的父亲(personA-> personB-> personC)。我对上述要求的mysql版本是

|id |person_name|
 1 | personA
 2 | personB
 3 | personC

my_parent

|id | person_id | parent|
1  |  3 |  2
2  |  2 |   1

但我对此感觉不对。可以任何mysql大师请给我一些更好的建议,还有一个sql语句来迭代检索人员层次结构。感谢

1 个答案:

答案 0 :(得分:3)

实际上你不需要两个表。相反,它通常使用一个表,其中父列的列引用同一个表中的另一个person_id

people

person_id | person_name | parent_id
1         | JSmith Jr   | 2
2         | JSmith Sr   | 3
3         | Grandpa     | NULL

要查询它,您可以对自己使用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个表:

people

person_id | person_name
1         | JSmith Jr
2         | JSmith Sr
3         | Grandpa
4         | Grandma
5         | MomSmith

relationships

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