MySQL MySQL中的自动增量varchar
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14038586/
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
Auto Increment varchar in MySQL
提问by Ye Wint
Is there a way to set primary key auto increment, type of varchar in mySql?
有没有办法在mySql中设置主键自动增量,varchar类型?
回答by John Woo
NONE. So far, AUTO_INCREMENT
can be set for INT
only. It needs to have your own logic to do that. eg,
无。到目前为止,AUTO_INCREMENT
只能设置为INT
。它需要有你自己的逻辑来做到这一点。例如,
- Get Last ID
- Get the INT part within the string
- Increment the value
- Concatenate
- Save to DB
- 获取最后一个 ID
- 获取字符串中的 INT 部分
- 增加值
- 连接
- 保存到数据库
回答by Nidhish Krishnan
Duplication of MySQL - how to use VARCHAR as AUTO INCREMENT Primary Key
复制MySQL - 如何使用 VARCHAR 作为 AUTO INCREMENT 主键
According to my point of view you have to change it as integer type.
Since AUTO_INCREMENT
is for INT
type only, moreover setting the field as PRIMARY KEY
which prevents duplication of values.
根据我的观点,您必须将其更改为整数类型。由于AUTO_INCREMENT
仅用于INT
类型,此外将字段设置为PRIMARY KEY
可防止值重复。
回答by Rahul
AutoIncrement fields are integer in mysql.
AutoIncrement 字段在 mysql 中是整数。
You can mirror the auto-increment field in a varchar field and create a trigger which updates the varchar field on insert/update.
您可以镜像 varchar 字段中的自动增量字段,并创建一个触发器,在插入/更新时更新 varchar 字段。
回答by kolapopo
for my experience, you can make Varcar ID as auto increment but you must have logic..let say
根据我的经验,您可以将 Varcar ID 设置为自动增量,但您必须有逻辑..让说
Dim crnum As String = "CR00001"
Dim iTemp As Integer = 0
iTemp = CInt(crnum.Substring(4, crnum.Length - 4)) '// get only the #'s from String and Convert them to Integer.
iTemp += 1 '// increase the ID # + 1.
crnum = crnum.Substring(0, 4) & iTemp.ToString("00000") '// set the ID back with String and #'s formatted to 5 digit #.
but you must do your own logic ,because after u run it for second time it will become duplicate primary key so, you must think your logic to apply your code. Anything is possible. ;)
但是你必须做你自己的逻辑,因为在你第二次运行它之后它会变成重复的主键,所以你必须考虑你的逻辑来应用你的代码。一切皆有可能。;)