父子关系

时间:2012-07-19 09:55:41

标签: sql-server

我想设计一个存储家庭成员的数据库,并且可以构建一个查询来查找谁是谁的父亲。简而言之就是父亲的儿子关系。

这就是我想出来的

家庭

|   id     |      Name    |
---------------------------
|   1      |   Ankit      |
---------------------------
|   2      |   Nishant    |

......

与此相关,以找到儿子和父亲的关系 我创建了另一个表

|  father_id    |    Son_id    |
--------------------------------
|   1           |       2      |
-------------------------------
.....

我觉得不正确可以有人指导我,需要写什么查询才能得到这样的关系。

提前致谢

修改

好的我现在尝试了查询,但不知怎的,我得到了错误 这就是我正在做的事情

select f.name as father_name, s.name as son_name
from (select family.name from family,father where father.father_id = family.id ) as f Inner Join
(select family.name from family,father where father.son_id = family.id) as s 
on
(family.id = father.father_id and family.id = father.son_id)

错误是

Msg 4104, Level 16, State 1, Line 2
The multi-part identifier "family.id" could not be bound.
Msg 4104, Level 16, State 1, Line 2
The multi-part identifier "father.father_id" could not be bound.
Msg 4104, Level 16, State 1, Line 2
The multi-part identifier "family.id" could not be bound.
Msg 4104, Level 16, State 1, Line 2
The multi-part identifier "father.son_id" could not be bound.

4 个答案:

答案 0 :(得分:2)

你所拥有的将会很好用,但你可以用一张桌子来完成它

Id   Name      Father
1    Ankit     Null
2    Nishant   1

答案 1 :(得分:1)

您的设计可行。它没有“错误”。

但还有另一种方式。

你可以在FAMILY表中有一个指向父行的FATHER_ID列。它是指向自身的外键。你不需要一个单独的表。

答案 2 :(得分:1)

不,没有错。

您可以根据关系表中的id

编写连接查询以加入自身
SELECT dad.name AS fathers_name, son.name AS sons_name
FROM father AS R

INNER JOIN family AS dad ON dad.id = R.father_id
INNER JOIN family AS son ON son.id = R.son_id

编辑:

这是我的sql server版本。我的工作没有任何问题。

答案 3 :(得分:0)

您的表格设计是正确的,但我会重命名表格PersonRelationShip

SELECT
  FamliyFather.name AS FatherName
  , FamliySon.name AS SonName
FROM
  Family AS FamliyFather
  INNER JOIN Father
    ON FamliyFather.id = Father.father_id
  INNER JOIN Family AS FamliySon
    ON Father.son_id = FamliySon.id

如果你需要祖先的完整树,你应该使用CTE。