我不是很熟悉数据库及其工作原理。从性能的角度(插入/更新/查询),使用字符串作主键是否比整数慢?
当前回答
有可能是一个非常大的误解有关字符串在数据库中。几乎每个人都认为数字的数据库表示比字符串更紧凑。他们认为db-s中的数字表示为内存中的数字。但事实并非如此。在大多数情况下,数字表示法更接近于字符串表示法。
使用数字或字符串的速度更依赖于索引,而不是类型本身。
其他回答
变量太多了。这取决于表的大小,索引,字符串键域的性质…
一般来说,整数会更快。但差别大到足以让人在意吗?这很难说。
另外,你选择字符串的动机是什么?数字型的自动递增键通常也容易得多。是语义上的吗?方便?复制/断开连接问题?你的回答可能会限制你的选择。这也会让你想起你忘记的第三个“混合”选项:Guids。
从性能的角度来看-与使用整数(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个字符串属性的整数组合在一起,但同样只是在需要时才这样做。
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.
使用什么作为主键并不重要,只要它是UNIQUE即可。如果您关心速度或良好的数据库设计,请使用int型,除非您计划复制数据,否则请使用GUID。
如果这是一个访问数据库或一些小应用程序,那么谁真的在乎。我认为,我们大多数开发人员之所以把旧的int或guid放在前面,是因为我们有一种方式来发展项目,并且您希望给自己留下发展的选择。
你为什么要用字符串作为主键?
我只需将主键设置为一个自动递增的整数字段,并在字符串字段上放置一个索引。
这样,如果您在表上进行搜索,它们应该相对较快,并且所有的连接和正常查找都不会受到速度的影响。
您还可以控制被索引的字符串字段的数量。换句话说,如果您认为这样就足够了,您可以说“只索引前5个字符”。或者如果您的数据可以相对相似,您可以索引整个字段。