MySQL - 如何使用 VARCHAR 作为 AUTO INCREMENT 主键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3455557/
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
MySQL - how to use VARCHAR as AUTO INCREMENT Primary Key
提问by Kenny Cason
I am using a VARCHAR as my primary key. I want to auto increment it (base 62, lower/upper case, numbers), However, the below code fails (for obvious reasons):
我使用 VARCHAR 作为我的主键。我想自动增加它(base 62,小写/大写,数字),但是,下面的代码失败(出于明显的原因):
CREATE TABLE IF NOT EXISTS `campaign` (
`account_id` BIGINT(20) NOT NULL,
`type` SMALLINT(5) NOT NULL,
`id` VARCHAR(16) NOT NULL AUTO_INCREMENT PRIMARY KEY
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
however, this works:
然而,这有效:
CREATE TABLE IF NOT EXISTS `campaign` (
`account_id` BIGINT(20) NOT NULL,
`type` SMALLINT(5) NOT NULL,
`id` VARCHAR(16) NOT NULL PRIMARY KEY
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
What is the best way to keep track of incrementation of 'id' myself? (Since auto_increment doesn't work). Do i need to make another table that contains the current iteration of ID? Or is there a better way to do this?
自己跟踪“id”增量的最佳方法是什么?(因为 auto_increment 不起作用)。我是否需要制作另一个包含当前 ID 迭代的表?或者有没有更好的方法来做到这一点?
EDIT:I want to clarify that I know that using INT is a auto_increment primary key is the logical way to go. This question is in response to some previous dialogue I saw. Thanks
编辑:我想澄清一下,我知道使用 INT 是 auto_increment 主键是合乎逻辑的方法。这个问题是对我之前看到的一些对话的回应。谢谢
采纳答案by Your Common Sense
you have to use an INT field
and translate it to whatever format you want at select time
您必须使用 INT 字段
并在选择时间将其转换为您想要的任何格式
回答by Gabriel Balbuena
example of a solution to your problem:
您的问题的解决方案示例:
create a file with a unique number and then increment with a function.
创建一个具有唯一编号的文件,然后使用函数递增。
the filename can be the prefix and the file binary content represent a number.
文件名可以是前缀,文件二进制内容代表一个数字。
when you need a new id to the reg invoque the function
当你需要一个新的 id 到 reg 调用函数时
Example
例子
String generateID(string A_PREFIX){
int id_value = parsetoInt(readFile(A_PREFIX).getLine())
int return_id_value = id_value++
return return_id_value
}
where "A_PREFIX-" is the file name wich you use to generate the id for the field.
其中“A_PREFIX-”是您用来生成字段 ID 的文件名。