天天看点

mysql主键字符串,MySQL-使用字符串作为主键

mysql主键字符串,MySQL-使用字符串作为主键

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

Let's say I offer a Web service. 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.

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).

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)

解决方案

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

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.

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.