1

我想建立联系人之间的家庭关系,并发现联系人之间的隐藏关系并使用 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 的父级。我怎么能这样做?

4

1 回答 1

1

您可以从另外 2 个表开始,1 个用于配置关系(类似于您当前的relation列),另一个用于配置在递归查找期间要遍历的关系。

Table: Relationship
Id: int
Description: string

Table: RelationshipToRelationship
FromRelationshipId: int
ToRelationshipId: int

数据如下所示:

关系

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

关系到关系

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

如果/当我解决它时,将更新一个可行的查询

我预见的问题:

  • 您提出了最简单的情况(我兄弟的父母是我的父母),但在其他情况下就崩溃了(我兄弟的孩子不是我的孩子)。
  • 标记关系的类似问题(您可以将我兄弟的父母标记为Parent-Child我,但您兄弟的孩子需要标记Brother-Brother-Parent-Child)。

一切都很快变得混乱。保持希望关联的每一方之间的直接关系不是更好吗(即,表中的另外 2 条记录将用户 4 和 2 连接为 Brother-Brother 和 4 和 1 作为 Parent-Child)?

于 2012-05-30T09:45:09.570 回答