SQL table: 与自身建立一对一关系?

SQL table: create 1-to-1 relationship with itself?

我想在 table 上与其自身建立一对一的关系。

我有一个 table MenuItem,但我希望这些项目能够有父项 MenuItem。一个项目只能有一个父项目,但一个项目可以是多个项目的父项目。

我目前正在使用 link table、MenuItemParent,但我不知道如何正确获取键和约束。它有两列:MenuItemIdParentId。两者都是 MenuItem table.
的外键 如果我将第一列或两列设为主键,我似乎会以一对多关系结束。 (我正在从数据库生成代码,因此我可以对其进行验证。)

如果我只将第一列作为主键,我最终会处于一种薛定谔状态,其中 MenuItem 既可以有一个父项也可以有多个父项(即生成的 POCO 有一个 MenuItem 属性 和一个 EntitySet<MenuItem> 属性。)我可以围绕这个构建我的代码,但是从模型或生成的代码中都不清楚究竟是怎样的关系呢

我错过了什么?

至于我为什么使用 link table,我正在尝试使用垂直分割,因为这些数据不会经常被访问。

A 1-1 relationship effectively partitions the attributes (columns) in a table into two tables. This is called vertical segmentation. This is often done for sub-classing the table entities, or, for another reason, if the usage patterns on the columns in the table indicate that a few of the columns need to be accessed significantly more often than the rest of the columns. (Say one or two columns will be accessed 1000s of times per second and the other 40 columns will be accessed only once a month). Partitioning the table in this way in effect will optimize the storage pattern for those two different queries.

发件人:

编辑:撇开过早优化不谈,我现在明白我可以简单地在 MenuItem table 中使用 ParentId 列,但这真的比使用 link [=45 更好吗=]?

去掉 "link" table。只需使用 ID (PK) 列和 ParentID (FK) 列设置您的 MenuItem table。设置外键关系(我假设你能弄清楚)。然后在 ParentIDID 列上设置 "Unique Key" 约束。

您应该使用外键向 table MenuItem 添加一个 ParentID 列。 这是有关如何执行此操作的示例。

alter table MenuItem
add ParentID int null;

alter table MenuItem
add constraint FK_MenuItemParent foreign key (ParentID) references MenuItem (ID);

现在你有一个层级 table,这意味着一个 menuitem 只能有一个 parent,但许多其他 menuitems 可以有相同的 [=14] =] 作为 parent

只有当你需要many to many关系时才需要Link Table,而这个

则不是

您也可以按照建议在两列上创建唯一索引,但要注意 ParentID 经常可能为空,因此请添加一个子句来解决这个问题

create unique nonclustered index idx_MenuParentID
on MenuItem(ID, ParentID)
where ParentID is not null;

我认为您应该尝试让 1 列是 PRIMARY KEY,另一列是 MenuItem 中的 FOREIGN KEY REFERENCES。因为在数据库中与自身的1-1关系称为自引用(更多信息可以搜索google),它不能有两个FOREIGN KEY。