我正在创建一个数据库表,我没有给它分配一个逻辑主键。每个表都应该有一个主键吗?
当前回答
Will you ever need to join this table to other tables? Do you need a way to uniquely identify a record? If the answer is yes, you need a primary key. Assume your data is something like a customer table that has the names of the people who are customers. There may be no natural key because you need the addresses, emails, phone numbers, etc. to determine if this Sally Smith is different from that Sally Smith and you will be storing that information in related tables as the person can have mulitple phones, addesses, emails, etc. Suppose Sally Smith marries John Jones and becomes Sally Jones. If you don't have an artifical key onthe table, when you update the name, you just changed 7 Sally Smiths to Sally Jones even though only one of them got married and changed her name. And of course in this case withouth an artificial key how do you know which Sally Smith lives in Chicago and which one lives in LA?
你说你没有自然的密钥,因此你也没有任何字段的组合来使其唯一,这使得人工密钥至关重要。
我发现,在没有天然密钥的情况下,人工密钥对于维护数据完整性是绝对必要的。如果您确实有一个自然键,您可以使用它作为键字段。但就我个人而言,除非自然键是一个字段,否则我仍然喜欢人工键和自然键上的唯一索引。如果你不放进去,你以后会后悔的。
其他回答
如果你正在使用Hibernate,不可能创建一个没有主键的实体。如果您正在使用使用普通sql/ddl脚本创建的现有数据库,并且没有添加主键,则此问题可能会产生问题
只要添加就可以了,以后你会后悔没有(选择,删除)。连接等)
几乎每次我创建一个没有主键的表时,我都认为我不需要主键,最终我会返回并添加一个主键。现在,我甚至用一个自动生成的标识字段作为主键来创建连接表。
除了少数非常罕见的情况(可能是多对多关系表,或者临时用于批量加载大量数据的表),我会使用以下说法:
如果它没有主键,它就不是表!
Marc
Will you ever need to join this table to other tables? Do you need a way to uniquely identify a record? If the answer is yes, you need a primary key. Assume your data is something like a customer table that has the names of the people who are customers. There may be no natural key because you need the addresses, emails, phone numbers, etc. to determine if this Sally Smith is different from that Sally Smith and you will be storing that information in related tables as the person can have mulitple phones, addesses, emails, etc. Suppose Sally Smith marries John Jones and becomes Sally Jones. If you don't have an artifical key onthe table, when you update the name, you just changed 7 Sally Smiths to Sally Jones even though only one of them got married and changed her name. And of course in this case withouth an artificial key how do you know which Sally Smith lives in Chicago and which one lives in LA?
你说你没有自然的密钥,因此你也没有任何字段的组合来使其唯一,这使得人工密钥至关重要。
我发现,在没有天然密钥的情况下,人工密钥对于维护数据完整性是绝对必要的。如果您确实有一个自然键,您可以使用它作为键字段。但就我个人而言,除非自然键是一个字段,否则我仍然喜欢人工键和自然键上的唯一索引。如果你不放进去,你以后会后悔的。
推荐文章
- 获得PostgreSQL数据库中当前连接数的正确查询
- MySQL数据库表中的最大记录数
- 从现有模式生成表关系图(SQL Server)
- HyperLogLog算法是如何工作的?
- 数据库和模式的区别
- 如何从命令行在windows中找到mysql数据目录
- 货币应该使用哪种数据类型?
- 如何找到MySQL的根密码
- 将表从一个数据库复制到另一个数据库的最简单方法?
- 什么是分片,为什么它很重要?
- 数据库触发器是必要的吗?
- 为什么我应该使用基于文档的数据库而不是关系数据库?
- 哪个更快/最好?SELECT *或SELECT columnn1, colum2, column3等
- 将值从同一表中的一列复制到另一列
- 什么是数据库池?