MySQL -使用字符串作为主键

时间:2021-08-07 02:09:51

I saw a similar post on Stack Overflow already, but wasn't quite satisfied.

我在Stack Overflow上看到过类似的帖子,但并不十分满意。

Let's say I offer a Web service. http://foo.com/SERVICEID

假设我提供一个Web服务。http://foo.com/SERVICEID

SERVICEID is a unique String ID used to reference the service (base 64, lower/uppercase + numbers), similar to how URL shortener services generate ID's for a URL.

SERVICEID是一个唯一的字符串ID,用于引用服务(base 64,小写+数字),类似于URL shortener服务如何为URL生成ID。

I understand that there are inherent performance issues with comparing strings versus integers.

我理解在比较字符串和整数之间存在固有的性能问题。

But I am curious of how to maximally optimize a primary key of type String.

但是我很好奇如何最大限度地优化字符串类型的主键。

I am using MySQL, (currently using MyISAM engine, though I admittedly don't understand all the engine differences).

我正在使用MySQL(目前使用MyISAM引擎,虽然我确实不理解所有的引擎差异)。

Thanks.

谢谢。

update for my purpose the string was actually just a base62 encoded integer, so the primary key was an integer, and since you're not likely to ever exceed bigint's size it just doesn't make too much sense to use anything else (for my particular use case)

出于我的目的进行更新字符串实际上只是一个base62编码的整数,所以主键是一个整数,由于您不太可能超过bigint的大小,因此使用其他任何东西(对于我的特定用例)都没有多大意义

1 个解决方案

#1


41  

There's nothing wrong with using a CHAR or VARCHAR as a primary key.

使用CHAR或VARCHAR作为主键没有任何问题。

Sure it'll take up a little more space than an INT in many cases, but there are many cases where it is the most logical choice and may even reduce the number of columns you need, improving efficiency, by avoiding the need to have a separate ID field.

当然,在许多情况下,它会比INT占用更多的空间,但是在很多情况下,它是最符合逻辑的选择,甚至可能减少所需的列的数量,通过避免使用单独的ID字段来提高效率。

For instance, country codes or state abbreviations already have standardised character codes and this would be a good reason to use a character based primary key rather than make up an arbitrary integer ID for each in addition.

例如,国家代码或国家缩写已经有了标准化的字符代码,这将是一个很好的理由来使用基于字符的主键,而不是为每个字符加上任意的整数ID。

#1


41  

There's nothing wrong with using a CHAR or VARCHAR as a primary key.

使用CHAR或VARCHAR作为主键没有任何问题。

Sure it'll take up a little more space than an INT in many cases, but there are many cases where it is the most logical choice and may even reduce the number of columns you need, improving efficiency, by avoiding the need to have a separate ID field.

当然,在许多情况下,它会比INT占用更多的空间,但是在很多情况下,它是最符合逻辑的选择,甚至可能减少所需的列的数量,通过避免使用单独的ID字段来提高效率。

For instance, country codes or state abbreviations already have standardised character codes and this would be a good reason to use a character based primary key rather than make up an arbitrary integer ID for each in addition.

例如,国家代码或国家缩写已经有了标准化的字符代码,这将是一个很好的理由来使用基于字符的主键,而不是为每个字符加上任意的整数ID。