我正在创建一个数据库表,我没有给它分配一个逻辑主键。每个表都应该有一个主键吗?
当前回答
只要添加就可以了,以后你会后悔没有(选择,删除)。连接等)
其他回答
我想找到一些官方的东西像这样- 15.6.2.1集群和次要索引- MySQL。
如果表没有PRIMARY KEY或合适的UNIQUE索引,InnoDB内部会在一个包含行ID值的合成列上生成一个名为GEN_CLUST_INDEX的隐藏聚集索引。行是根据InnoDB分配给这样一个表中的行的ID来排序的。行ID是一个6字节的字段,随着新行插入而单调增加。因此,按行ID排序的行在物理上按插入顺序排列。
为什么不自己创建主键呢?此外,ORM不能识别这个隐藏的ID,这意味着您不能在代码中使用ID。
除了少数非常罕见的情况(可能是多对多关系表,或者临时用于批量加载大量数据的表),我会使用以下说法:
如果它没有主键,它就不是表!
Marc
几乎每次我创建一个没有主键的表时,我都认为我不需要主键,最终我会返回并添加一个主键。现在,我甚至用一个自动生成的标识字段作为主键来创建连接表。
虽然来晚了,但我想补充一下我的观点:
每个表都应该有一个主键吗?
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).
总之,在遵循实体/关系模型的事务应用程序中,为几乎(如果不是)所有表设置主键非常有意义。如果您决定跳过表的主键,请确保您有一个很好的理由,并准备为您的决定辩护。
不同意建议的答案。简短的回答是:不。
主键的作用是唯一地标识表上的一行,以便与另一个表形成关系。传统上,用于此目的的是一个自动递增的整数值,但也有一些变化。
但在某些情况下,例如记录时间序列数据,根本不需要这样的键,只需要占用内存。使一行唯一很简单……不需要!
举个小例子: 表A: LogData
Columns: DateAndTime, UserId, AttribA, AttribB, AttribC etc...
不需要主键。
表B:用户
Columns: Id, FirstName, LastName etc.
用来作为LogData表的“外键”的主键(Id)。