我不是很熟悉数据库及其工作原理。从性能的角度(插入/更新/查询),使用字符串作主键是否比整数慢?
当前回答
有可能是一个非常大的误解有关字符串在数据库中。几乎每个人都认为数字的数据库表示比字符串更紧凑。他们认为db-s中的数字表示为内存中的数字。但事实并非如此。在大多数情况下,数字表示法更接近于字符串表示法。
使用数字或字符串的速度更依赖于索引,而不是类型本身。
其他回答
Technically yes, but if a string makes sense to be the primary key then you should probably use it. This all depends on the size of the table you're making it for and the length of the string that is going to be the primary key (longer strings == harder to compare). I wouldn't necessarily use a string for a table that has millions of rows, but the amount of performance slowdown you'll get by using a string on smaller tables will be minuscule to the headaches that you can have by having an integer that doesn't mean anything in relation to the data.
从性能的角度来看-与使用整数(PK)实现的性能相比,Yes字符串(PK)将降低性能,其中PK—>主键。
From requirement standpoint - Although this is not a part of your question still I would like to mention. When we are handling huge data across different tables we generally look for the probable set of keys that can be set for a particular table. This is primarily because there are many tables and mostly each or some table would be related to the other through some relation ( a concept of Foreign Key ). Therefore we really cannot always choose an integer as a Primary Key, rather we go for a combination of 3, 4 or 5 attributes as the primary key for that tables. And those keys can be used as a foreign key when we would relate the records with some other table. This makes it useful to relate the records across different tables when required.
因此,为了优化使用-我们总是将1或2个具有1或2个字符串属性的整数组合在一起,但同样只是在需要时才这样做。
是的,但除非您希望有数百万行,否则不使用基于字符串的键(因为它较慢)通常是“过早优化”。毕竟,字符串存储为大数字,而数字键通常存储为较小的数字。
不过,要注意的一件事是,如果您在任意键上聚集了索引,并且在索引中进行了大量的非顺序插入。写入的每一行都将导致索引重新写入。如果您正在进行批量插入,这确实会降低过程的速度。
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.
变量太多了。这取决于表的大小,索引,字符串键域的性质…
一般来说,整数会更快。但差别大到足以让人在意吗?这很难说。
另外,你选择字符串的动机是什么?数字型的自动递增键通常也容易得多。是语义上的吗?方便?复制/断开连接问题?你的回答可能会限制你的选择。这也会让你想起你忘记的第三个“混合”选项:Guids。
推荐文章
- 我如何检查如果一个变量是JavaScript字符串?
- 如何显示有两个小数点后的浮点数?
- 在MySQL中检测值是否为number
- MySQL中两个日期之间的差异
- 使用SQL查询查找最近的纬度/经度
- 在Lua中拆分字符串?
- 模式、表和数据库之间的区别是什么?
- 将一列的多个结果行连接为一列,按另一列分组
- 如何在Python中按字母顺序排序字符串中的字母
- 检查MySQL表是否存在而不使用“select from”语法?
- python: SyntaxError: EOL扫描字符串文字
- PHP子字符串提取。获取第一个'/'之前的字符串或整个字符串
- 我看到VARCHAR(255)如此频繁地使用(而不是其他长度),有什么好的原因吗?
- 使用pgadmin连接到heroku数据库
- 在PostgreSQL中快速发现表的行数