MySQL - 使用字符串作为主键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3455297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 16:48:17  来源:igfitidea点击:

MySQL - using String as Primary Key

mysqloptimizationprimary-key-design

提问by Kenny Cason

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(基数为 64,小写/大写 + 数字),类似于 URL 缩短服务为 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.

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

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

我正在使用 MySQL,(目前使用的是 MyISAM 引擎,尽管我承认我不了解所有引擎差异)。

Thanks.

谢谢。

updatefor 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 的大小,所以使用其他任何东西都没有太大意义(对于我的特定用例)

回答by thomasrutter

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 的一个很好的理由。

回答by dolmen

If your external ID is base64, your internal ID is a binary string. Use that as the key in your database with type BINARY(n)(if fixed length) or VARBINARYif variable length. The binary version is 3/4 shorter than the base64 one.

如果您的外部 ID 是 base64,则您的内部 ID 是一个二进制字符串。使用它作为类型BINARY(n)(如果固定长度)或VARBINARY可变长度的数据库中的键。二进制版本比 base64 短 3/4。

And just convert from/to base64 in your service.

只需在您的服务中从/到 base64 转换即可。