我不是很熟悉数据库及其工作原理。从性能的角度(插入/更新/查询),使用字符串作主键是否比整数慢?
当前回答
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.
其他回答
你为什么要用字符串作为主键?
我只需将主键设置为一个自动递增的整数字段,并在字符串字段上放置一个索引。
这样,如果您在表上进行搜索,它们应该相对较快,并且所有的连接和正常查找都不会受到速度的影响。
您还可以控制被索引的字符串字段的数量。换句话说,如果您认为这样就足够了,您可以说“只索引前5个字符”。或者如果您的数据可以相对相似,您可以索引整个字段。
是的,但除非您希望有数百万行,否则不使用基于字符串的键(因为它较慢)通常是“过早优化”。毕竟,字符串存储为大数字,而数字键通常存储为较小的数字。
不过,要注意的一件事是,如果您在任意键上聚集了索引,并且在索引中进行了大量的非顺序插入。写入的每一行都将导致索引重新写入。如果您正在进行批量插入,这确实会降低过程的速度。
有可能是一个非常大的误解有关字符串在数据库中。几乎每个人都认为数字的数据库表示比字符串更紧凑。他们认为db-s中的数字表示为内存中的数字。但事实并非如此。在大多数情况下,数字表示法更接近于字符串表示法。
使用数字或字符串的速度更依赖于索引,而不是类型本身。
在PK列中使用整数有两个原因:
我们可以为自动递增的整数字段设置标识。 当我们创建pk时,db会创建一个索引(Cluster或Non Cluster),在数据存储到表之前对其进行排序。通过在PK上使用标识,优化器在保存记录之前不需要检查排序顺序。这提高了大表的性能。
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.