2012-05-30 54 views
1

我想建立觸點之間的家庭關係,發現觸點之間隱藏的relaions和SQL Server使用遞歸表現出來。 例如: 我有這樣的表,其中包含:建立家庭關係的項目

User_id_1 User_id_2 relation 
1   2   Parent-child 
2   3   Brother-brother 
3   4   Brother-brother 

我的存儲過程應該發現針對特定用戶ID的所有關係。 如果用user_id = 4, 調用這個sp,它應該給我user_id = 4的所有關係,並且它應該知道比4是3和2的兄弟, 和1是4的父親。 我該怎麼做?

回答

1

您可以從2個表格開始,1個配置關係(類似於您當前的relation列),另一個可以配置在遞歸查找期間要走哪些關係。

Table: Relationship 
Id: int 
Description: string 

Table: RelationshipToRelationship 
FromRelationshipId: int 
ToRelationshipId: int 

數據是這樣的:

關係

Id Description 
== =============== 
1 Brother-Brother 
2 Parent-Child 

RelationshipToRelationship

FromRelationshipId ToRelationshipId 
================== ================ 
1     1 
1     2 

將一個可行的查詢更新,如果/當我工作了

問題我可以預見:

  • 你呈現最簡單的情況(我哥哥的父母就是我的父母),但是分崩離析的其他情況下(我哥哥的孩子是不是我的孩子)。
  • 用於標記的關係類似的問題(你可以標我兄弟的母公司爲Parent-Child給我,但你的兄弟的孩子需要被標記Brother-Brother-Parent-Child)。

所有被混淆非常快。你會不會更好地保持你想要關聯的每一方之間的直接關係(例如,你的表格中的另外2條記錄將兄弟 - 兄弟和4 & 1鏈接成父母 - 孩子)?

+0

確定THX ,,但我使用SQL Server的功能和SPS獲得特定用戶的所有關係,我想知道什麼想要一個遞歸技術? – Haneen

+0

我在第一個記錄是指1是2, – Haneen

+0

其他記錄父表示2是兄弟3和3兄弟4日 – Haneen