我不是很熟悉数据库及其工作原理。从性能的角度(插入/更新/查询),使用字符串作主键是否比整数慢?
当前回答
Strings are slower in joins and in real life they are very rarely really unique (even when they are supposed to be). The only advantage is that they can reduce the number of joins if you are joining to the primary table only to get the name. However, strings are also often subject to change thus creating the problem of having to fix all related records when the company name changes or the person gets married. This can be a huge performance hit and if all tables that should be related somehow are not related (this happens more often than you think), then you might have data mismatches as well. An integer that will never change through the life of the record is a far safer choice from a data integrity standpoint as well as from a performance standpoint. Natural keys are usually not so good for maintenance of the data.
我还想指出,两者的最佳方法通常是使用自递增键(或者在某些特殊情况下,使用GUID)作为PK,然后在自然键上放置唯一索引。您可以获得更快的连接,不会得到重复的记录,也不必因为公司名称更改而更新一百万个子记录。
其他回答
不要担心性能,直到您获得了一个简单而合理的设计,该设计与数据描述的主题一致,并且非常适合数据的预期用途。然后,如果出现性能问题,您可以通过调整系统来处理它们。
在这种情况下,使用字符串作为自然的主键几乎总是更好的,只要您可以信任它。如果是字符串也不用担心,只要字符串足够短,比如说最多25个字符。就性能而言,你不会付出很大的代价。
数据输入人员或自动数据源是否总是为假定的自然键提供一个值,还是有时会省略?输入数据偶尔会出错吗?如果是,如何检测和纠正错误?
指定查询的程序员和交互用户能够使用自然键来获得他们想要的东西吗?
如果你不相信天然的钥匙,那就找一个替代品。如果你发明了一个代理,你也可以发明一个整数。然后,您必须考虑是否对用户社区隐藏代理。一些没有隐藏代理键的开发人员后来后悔了。
有可能是一个非常大的误解有关字符串在数据库中。几乎每个人都认为数字的数据库表示比字符串更紧凑。他们认为db-s中的数字表示为内存中的数字。但事实并非如此。在大多数情况下,数字表示法更接近于字符串表示法。
使用数字或字符串的速度更依赖于索引,而不是类型本身。
Inserts to a table having a clustered index where the insertion occurs in the middle of the sequence DOES NOT cause the index to be rewritten. It does not cause the pages comprising the data to be rewritten. If there is room on the page where the row will go, then it is placed in that page. The single page will be reformatted to place the row in the right place in the page. When the page is full, a page split will happen, with half of the rows on the page going to one page, and half going on the other. The pages are then relinked into the linked list of pages that comprise a tables data that has the clustered index. At most, you will end up writing 2 pages of database.
在PK列中使用整数有两个原因:
我们可以为自动递增的整数字段设置标识。 当我们创建pk时,db会创建一个索引(Cluster或Non Cluster),在数据存储到表之前对其进行排序。通过在PK上使用标识,优化器在保存记录之前不需要检查排序顺序。这提高了大表的性能。
是的,但除非您希望有数百万行,否则不使用基于字符串的键(因为它较慢)通常是“过早优化”。毕竟,字符串存储为大数字,而数字键通常存储为较小的数字。
不过,要注意的一件事是,如果您在任意键上聚集了索引,并且在索引中进行了大量的非顺序插入。写入的每一行都将导致索引重新写入。如果您正在进行批量插入,这确实会降低过程的速度。
推荐文章
- 我如何在Swift连接字符串?
- 如何连接列在Postgres选择?
- 如何获得一个变量值,如果变量名存储为字符串?
- 有人可以对SQL查询进行版权保护吗?
- 在Ruby中不创建新字符串而修饰字符串的规范方法是什么?
- 为什么不是字符串。空一个常数?
- 数据库触发器是必要的吗?
- 如何知道MySQL表最近一次更新?
- 如何转储一些SQLite3表的数据?
- 如何创建一个SQL Server函数“连接”多行从一个子查询到一个单独的分隔字段?
- 在MySQL中的一个查询中更新多个具有不同值的行
- 在SQL中更新多个列
- 如何删除表中特定列的第一个字符?
- MySQL OR与IN性能
- 为什么我应该使用基于文档的数据库而不是关系数据库?