父子关系

问题描述:

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

这是我想出了

家庭

| 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. 
+0

为什么你觉得这是不正确的?表格本身的关系完全可以。 – 2012-07-19 09:58:10

+0

我有一个想法,它会起作用,但不知道这是做这种事的正确方法,因为人们可能会进入自己的身份证。一个人不能成为他自己的父亲。所以我有疑问。 – 2012-07-19 11:13:11

做这件事不,那里有什么错。

你可以写一个联接查询基于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版本。我有这个工作没有任何问题。

+0

我在访问时做了这个,所以你可能不需要sql server的括号。先做一个测试查询。 – Dpolehonski 2012-07-19 10:20:38

+0

我试过你的方式,但不知何故在查询中出现错误,请你能帮助我。我刚刚编辑了这个问题 – 2012-07-20 08:40:31

+0

立即尝试编辑后的版本。我在sql server 2012中建立了这个 – Dpolehonski 2012-07-20 10:20:29

您的设计可以工作。它没有什么“错误”。

但还有另一种方法。

您可以在FAMILY表中指定父行的FATHER_ID列。这是一个指向自己的外键。你不需要这样一个单独的表。

+0

你可以请指导我的查询..我编辑我的问题。 – 2012-07-20 08:42:52

你有什么会工作得很好,但你可以用一个表

Id Name  Father 
1 Ankit  Null 
2 Nishant 1 

你的表的设计是正确的,但我会如果你需要你的祖先,你应该使用一个CTE的整个树改名为表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