我不是很熟悉数据库及其工作原理。从性能的角度(插入/更新/查询),使用字符串作主键是否比整数慢?


当前回答

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.

其他回答

我可能会使用一个整数作为你的主键,然后把你的字符串(我假设它是某种ID)作为一个单独的列。

create table sample (
  sample_pk             INT NOT NULL AUTO_INCREMENT,
  sample_id             VARCHAR(100) NOT NULL,
  ...
  PRIMARY KEY(sample_pk)
);

您总是可以对字符串(ID)列(其中sample_id =…)进行有条件的查询和连接。

变量太多了。这取决于表的大小,索引,字符串键域的性质…

一般来说,整数会更快。但差别大到足以让人在意吗?这很难说。

另外,你选择字符串的动机是什么?数字型的自动递增键通常也容易得多。是语义上的吗?方便?复制/断开连接问题?你的回答可能会限制你的选择。这也会让你想起你忘记的第三个“混合”选项:Guids。

指数意味着大量的比较。

通常,字符串比整数长,并且可以应用排序规则进行比较,因此比较字符串通常比比较整数需要更多的计算量。

不过,有时使用字符串作为主键要比使用字符串与数字id表进行额外的连接更快。

使用string作为主键的另一个问题是,由于索引不断按顺序排列,当创建一个新键时,索引必须重新排序……如果使用自动编号整数,则新键只添加到索引的末尾。

你为什么要用字符串作为主键?

我只需将主键设置为一个自动递增的整数字段,并在字符串字段上放置一个索引。

这样,如果您在表上进行搜索,它们应该相对较快,并且所有的连接和正常查找都不会受到速度的影响。

您还可以控制被索引的字符串字段的数量。换句话说,如果您认为这样就足够了,您可以说“只索引前5个字符”。或者如果您的数据可以相对相似,您可以索引整个字段。