我不是很熟悉数据库及其工作原理。从性能的角度(插入/更新/查询),使用字符串作主键是否比整数慢?
当前回答
变量太多了。这取决于表的大小,索引,字符串键域的性质…
一般来说,整数会更快。但差别大到足以让人在意吗?这很难说。
另外,你选择字符串的动机是什么?数字型的自动递增键通常也容易得多。是语义上的吗?方便?复制/断开连接问题?你的回答可能会限制你的选择。这也会让你想起你忘记的第三个“混合”选项:Guids。
其他回答
指数意味着大量的比较。
通常,字符串比整数长,并且可以应用排序规则进行比较,因此比较字符串通常比比较整数需要更多的计算量。
不过,有时使用字符串作为主键要比使用字符串与数字id表进行额外的连接更快。
你为什么要用字符串作为主键?
我只需将主键设置为一个自动递增的整数字段,并在字符串字段上放置一个索引。
这样,如果您在表上进行搜索,它们应该相对较快,并且所有的连接和正常查找都不会受到速度的影响。
您还可以控制被索引的字符串字段的数量。换句话说,如果您认为这样就足够了,您可以说“只索引前5个字符”。或者如果您的数据可以相对相似,您可以索引整个字段。
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.
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,然后在自然键上放置唯一索引。您可以获得更快的连接,不会得到重复的记录,也不必因为公司名称更改而更新一百万个子记录。
使用string作为主键的另一个问题是,由于索引不断按顺序排列,当创建一个新键时,索引必须重新排序……如果使用自动编号整数,则新键只添加到索引的末尾。
推荐文章
- 我如何在Swift连接字符串?
- 如何连接列在Postgres选择?
- 如何获得一个变量值,如果变量名存储为字符串?
- 有人可以对SQL查询进行版权保护吗?
- 在Ruby中不创建新字符串而修饰字符串的规范方法是什么?
- 为什么不是字符串。空一个常数?
- 数据库触发器是必要的吗?
- 如何知道MySQL表最近一次更新?
- 如何转储一些SQLite3表的数据?
- 如何创建一个SQL Server函数“连接”多行从一个子查询到一个单独的分隔字段?
- 在MySQL中的一个查询中更新多个具有不同值的行
- 在SQL中更新多个列
- 如何删除表中特定列的第一个字符?
- MySQL OR与IN性能
- 为什么我应该使用基于文档的数据库而不是关系数据库?