自引用表的部分键

时间:2013-09-09 07:22:08

标签: sql sql-server database-design foreign-keys self-reference

我正在设计一个数据表(-s)来存储股东名单。如果股东是被提名人,则会披露股东名单。这些都需要有一堆类似的参考。因此,我想将所有内容存储在一个表中。被提名人是注册股东,因此,他们在系统中有一个账号,我从中获得数据。与此相反,来自被提名人披露的股东没有自己的账号,并且分享了被提名人的账号。

我在表格中添加了一个uniquifier。我想假设所有注册股东和被提名人在这个领域都有0。披露清单(通过被提名人工作的非登记股份所有人)在该无统一申请人中具有高于零的值。基本上是编号列表。

我需要知道被披露的股东所属的被提名人。所以,我们正在进行自我参考。如果不是uniquifier字段,那可能是好的。在主键的一部分上创建外键并假设uniquifier字段中存在零是非法的。那么,请你推荐一个演练。

为了更好地解释,以下是摘录:

Create Table Account (
  AccountId Int,
  Uniquifier Int,

  NomineeId Int,

  Constraint PK$Account Primary Key (AccountId, Uniquifier)     
)

我想做的是:

Alter Table Account 
  Add Constraint FK$SelfReference Foreign Key (NomineeId) References Account (AccountId)

这是非法的,因为

There are no primary or candidate keys in the referenced table 'Account' that match the referencing column list in the foreign key 'FK$SelfReference'.

感谢任何帮助。

1 个答案:

答案 0 :(得分:3)

您可以添加computed column,{F}应该强制实施,0NULL。然后可以在外键引用中使用它:

Create Table Account (
  AccountId Int,
  Uniquifier Int,

  NomineeId Int,
  NomineeXRef as CASE WHEN Uniqueifier > 0 THEN 0 END persisted

  Constraint PK$Account Primary Key (AccountId, Uniquifier),
  Constraint FK$SelfReference Foreign Key (NomineeId,NomineeXRef) References Account (AccountId, Uniquifier)     
)
相关问题