我正在创建一个数据库表,我没有给它分配一个逻辑主键。每个表都应该有一个主键吗?


当前回答

我总是有一个主键,即使一开始我还没有想到它的目的。有几次,当我最终需要在一个没有PK的表中输入PK时,总是会遇到更多的麻烦。我认为总是有一个人会有更多的好处。

其他回答

最好有一个主键。通过这种方式,它满足了第一种标准形式,并允许您继续沿着数据库规范化路径进行。

正如其他人所述,有一些理由不使用主键,但如果有主键,大多数情况下不会受到损害

我总是有一个主键,即使一开始我还没有想到它的目的。有几次,当我最终需要在一个没有PK的表中输入PK时,总是会遇到更多的麻烦。我认为总是有一个人会有更多的好处。

几乎每次我创建一个没有主键的表时,我都认为我不需要主键,最终我会返回并添加一个主键。现在,我甚至用一个自动生成的标识字段作为主键来创建连接表。

如果你正在使用Hibernate,不可能创建一个没有主键的实体。如果您正在使用使用普通sql/ddl脚本创建的现有数据库,并且没有添加主键,则此问题可能会产生问题

虽然来晚了,但我想补充一下我的观点:

每个表都应该有一个主键吗?

If you are talking about "Relational Albegra", the answer is Yes. Modelling data this way requires the entities and tables to have a primary key. The problem with relational algebra (apart from the fact there are like 20 different, mismatching flavors of it), is that it only exists on paper. You can't build real world applications using relational algebra. Now, if you are talking about databases from real world apps, they partially/mostly adhere to the relational algebra, by taking the best of it and by overlooking other parts of it. Also, database engines offer massive non-relational functionality nowadays (it's 2020 now). So in this case the answer is No. In any case, 99.9% of my real world tables have a primary key, but there are justifiable exceptions. Case in point: event/log tables (multiple indexes, but not a single key in sight).

总之,在遵循实体/关系模型的事务应用程序中,为几乎(如果不是)所有表设置主键非常有意义。如果您决定跳过表的主键,请确保您有一个很好的理由,并准备为您的决定辩护。