2012-07-19 125 views
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. 
+0

爲什麼你覺得這是不正確的?表格本身的關係完全可以。 – 2012-07-19 09:58:10

+0

我有一個想法,它會起作用,但不知道這是做這種事的正確方法,因爲人們可能會進入自己的身份證。一個人不能成爲他自己的父親。所以我有疑問。 – 2012-07-19 11:13:11

回答

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版本。我有這個工作沒有任何問題。

+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

1

您的設計可以工作。它沒有什麼「錯誤」。

但還有另一種方法。

您可以在FAMILY表中指定父行的FATHER_ID列。這是一個指向自己的外鍵。你不需要這樣一個單獨的表。

+0

你可以請指導我的查詢..我編輯我的問題。 – 2012-07-20 08:42:52

2

你有什麼會工作得很好,但你可以用一個表

Id Name  Father 
1 Ankit  Null 
2 Nishant 1 
0

你的表的設計是正確的,但我會如果你需要你的祖先,你應該使用一個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