【问题标题】:Should my intermediate table contain a composite PK or a unique index我的中间表应该包含复合 PK 还是唯一索引
【发布时间】:2011-03-29 21:38:01
【问题描述】:

假设我有一个Products 表、ProductsCategory 表和一个Category 表。

ProductsCategory 表有两列:ProductIDCategoryID。我应该在两列上使用复合主键还是唯一索引?

此外,如果我使用索引,我可以将其设为唯一索引或键。

【问题讨论】:

    标签: sql-server database-design


    【解决方案1】:

    也可以使用复合键 - 当您已经拥有复合主键的唯一性语义时,无需添加唯一索引。

    【讨论】:

      【解决方案2】:

      您必须使用 on delete cascade 选项创建两个表的双向外键。 因为如果您删除其中一个类别,那么它必须删除 ProductCategory 上的关系行。

      我的意思是你可以这样使用:

      alter table ProductsCategory add constraint ForeignKey1 foreign key (ProductId) references Products (ID) ON DELETE CASCADE;
      alter table ProductsCategory add constraint ForeignKey2 foreign key (CategoryId) references Category (ID) ON DELETE CASCADE;
      

      【讨论】:

        猜你喜欢
        • 2013-01-13
        • 2011-01-12
        • 1970-01-01
        • 1970-01-01
        • 2011-04-17
        • 2014-07-17
        • 1970-01-01
        • 1970-01-01
        • 2011-07-02
        相关资源
        最近更新 更多