0

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

这就是我想出的

家庭

|   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

4 回答 4

2

你所拥有的一切都很好,但你可以用一张桌子来做

Id   Name      Father
1    Ankit     Null
2    Nishant   1
于 2012-07-19T09:58:43.093 回答
1

你的设计可以工作。它没有任何“错误”。

但还有另一种方式。

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

于 2012-07-19T09:58:25.313 回答
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 版本。我有这个工作没有任何问题。

于 2012-07-19T10:20:05.680 回答
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。

于 2012-07-20T12:13:20.490 回答