这个“映射”表是否需要一个单独的 Id 列?

Jos*_*ell 11 database-design sql-server referential-integrity

我有一个表Producers和一个表Products,两者都是以下形式:

  • Id - int, 主键
  • Name - nvarchar

Producer 可以携带多个产品,因此我将创建一个名为的表ProducerDetails,该表将具有:

  • ProducerId - int, 外键 Producers.Id
  • ProductId - int, 外键 Products.Id

然后我开始质疑自己,所以我想我会问专家。Id在我的ProducerDetails表中有一个额外的(int,主键)列会更好的数据库设计吗?或者这是不必要的?

如果这有什么不同,我正在使用 SQL-Server 2008 R2。

编辑- 我相信这些表之间的关系是多对多的,抱歉我没有说清楚。一个生产者可以携带多种类型的产品,同一产品可以由多个不同的生产者生产。

如果这个问题过于简单,我深表歉意,参照完整性/数据库设计不是我的强项(尽管我正在努力改进)。

Aar*_*and 7

不,向该表添加额外的“主键”没有任何价值。你的连接只会引用ProducerIDand ProductID,所以它只是自重。恕我直言。

尽管我同意@Shark 的观点,这里似乎甚至不需要连接表,除非您不以任何方式更改现有表的架构。

顺便说一句,我也认为完整命名您的主要标识符是值得的(例如,Products.ProductID而不是Products.ID),以便标识符在整个架构中始终如一地命名。


Tho*_*ger 6

如果生产者和产品之间存在一对多关系(换句话说,一个产品只能属于一个生产者),那么直接在Products表中放置外键引用是有意义的:

一对多

create table Producer
(
    id int identity(1, 1) not null primary key clustered,
    Name varchar(100) not null
)
go

create table Product
(
    id int identity(1, 1) not null,
    Name varchar(100) not null,
    ProducerId int not null foreign key references Producer(id)
)
go
Run Code Online (Sandbox Code Playgroud)

但是,如果这可能是多对多关系,那么最好的办法是使用 Join 表。

多对多

create table Producer
(
    id int identity(1, 1) not null primary key clustered,
    Name varchar(100) not null
)
go

create table Product
(
    id int identity(1, 1) not null primary key clustered,
    Name varchar(100) not null
)
go

create table ProductProducer
(
    ProductId int not null foreign key references Product(id),
    ProducerId int not null foreign key references Producer(id)
)
go

-- adding the primary key also ensures uniqueness
alter table ProductProducer
add constraint PK_ProductProducer 
primary key (ProductId, ProducerId)
go
Run Code Online (Sandbox Code Playgroud)

如果您决定使用 Join 表,则不需要额外的键,因为 的组合ProductId/ProducerId最终将是唯一的。 你可以把它们作为一个复合键,这样你就不需要额外Id的领域ProductProducer