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サーバーのバージョンです。私はこれを問題なく動作させています。

于 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 に答える