我应该使用联结表吗?

时间:2017-04-02 11:10:46

标签: sql sql-server asp.net-mvc-5 relationship

我正在使用asp.net mvc5开发一个网站,而且我正在与在该领域拥有长期经验的dba合作。 我们对下表之间的以下关系存在冲突。

Award table
-ID
-.. the table fields
-supplierID
-employeeID
-otherID

Supplier
-ID
-.. the table fields

employee table
-ID
-.. the table fields

other table
-ID
-.. the table fields

奖励表中的最后三行是奖励的受益人类型。你不可能有多个受益人。

所以我的建议是使用链接表"受益人"连接不同的受益人和#34;和#34;奖项"表

你怎么想?

1 个答案:

答案 0 :(得分:0)

你有一个"一个"关系。这在SQL中很棘手,使用三列的方法是一种很好的方法。为什么?它允许正确的外键声明。

我会寻找一个像这样的表定义:

create table Awards (
    awardsId int identity primary key,
    . . .
    supplierId int,
    employeeID int,
    otherID int,
    beneficiaryType as (case when supplierId is not null then 'S'
                             when employeeId is not null then 'E'
                             when otherId is not null then 'O'
                        end),
    constraint chk_beneficiary
        check ( (supplierId is not null and employeeId is null and otherid is null) or
                (supplierId is null and employeeId is not null and otherid is null) or
                (supplierId is null and employeeId is null and otherid is not null)
             ),      
    constraint fk_awards_supplierId foreign key (supplierId) references Suppliers(supplierId),
    constraint fk_awards_employeeId foreign key (employeeId) references Employees(employeeId),
    constraint fk_awards_supplierId foreign key (otherId) references Others(otherId)
);

如果添加其他类型的受益人并不常见,那么数据库维护不是一个大问题。

我应该注意,您也可以使用" generic"列和持久计算列:

create table Awards (
    awardsId int identity primary key,
    . . .
    beneficiaryType char(1) not null,
    beneficiaryId int not null,
    constraint chk_awards_beneficiaryType check (beneficiaryType in ('E', 'S', 'O')),
    supplierId as (case when beneficiaryType = 'S' then beneficiaryId end) persisted,
    employeeID as (case when beneficiaryType = 'E' then beneficiaryId end) persisted,
    otherID as (case when beneficiaryType = 'O' then beneficiaryId end) persisted,
    constraint fk_awards_supplierId foreign key (supplierId) references Suppliers(supplierId),
    constraint fk_awards_employeeId foreign key (employeeId) references Employees(employeeId),
    constraint fk_awards_supplierId foreign key (otherId) references Others(otherId)
);

因为必须保留计算列以便用作外键,所以这不会节省空间。但是,添加新类型只是一件事:

  • 更改check
  • beneficiaryType约束
  • 添加新的计算列
  • 添加新的外键约束

这确实要求所有表的所有ID都具有相同的类型。但是,我(几乎)总是使用标识列作为主键,因此在我设计的任何数据库中都会自动生效。